diff --git a/README.md b/README.md index 7d0b3f6d993ced3a39c482f66f5dbf73e16b88c3..16aeb2841fdb1ce21417eb16874a8af3af0fa24f 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,19 @@ --- title: Neuron Runner -emoji: 💻 -colorFrom: green -colorTo: blue +emoji: 🧠 +colorFrom: blue +colorTo: purple sdk: static pinned: false +license: mit +short_description: RL neural net learns a platformer in real time --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# Neuron Runner + +A browser-based reinforcement learning demo where a neural network learns to play a 2D platformer (Mario-style) in real time. + +- **MLP mode** — classic two-layer perceptron policy +- **CoFrNet mode** — continued-fraction network (exotic architecture from the paper) +- **REINFORCE** policy-gradient training, running live in-browser via TensorFlow.js (WebGPU / CPU) +- Real-time neural activation visualizations powered by Three.js diff --git a/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 b/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..0acaaff03d4bb7606de02a827aeee338e5a86910 Binary files /dev/null and b/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 differ diff --git a/assets/KaTeX_AMS-Regular-DMm9YOAa.woff b/assets/KaTeX_AMS-Regular-DMm9YOAa.woff new file mode 100644 index 0000000000000000000000000000000000000000..b804d7b33a3fa5b2587d2d1d55006aed678e3eb2 Binary files /dev/null and b/assets/KaTeX_AMS-Regular-DMm9YOAa.woff differ diff --git a/assets/KaTeX_AMS-Regular-DRggAlZN.ttf b/assets/KaTeX_AMS-Regular-DRggAlZN.ttf new file mode 100644 index 0000000000000000000000000000000000000000..c6f9a5e7c03f9e64e9c7b4773a8e37ade8eaf406 Binary files /dev/null and b/assets/KaTeX_AMS-Regular-DRggAlZN.ttf differ diff --git a/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf b/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf new file mode 100644 index 0000000000000000000000000000000000000000..9ff4a5e04421e5107f74c28e27354e0b2a4e7ef8 Binary files /dev/null and b/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf differ diff --git a/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff b/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff new file mode 100644 index 0000000000000000000000000000000000000000..9759710d1d3e16eb10012d56babb73f2479ba9f0 Binary files /dev/null and b/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff differ diff --git a/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 b/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..f390922eceffe1f6dfb81a3dc086a92d98171b02 Binary files /dev/null and b/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 differ diff --git a/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff b/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff new file mode 100644 index 0000000000000000000000000000000000000000..9bdd534fd2beb9b878f0219da9d63ffba56677e2 Binary files /dev/null and b/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff differ diff --git a/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 b/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..75344a1f98e37e2c631e178065854c3a81fb842f Binary files /dev/null and b/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 differ diff --git a/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf b/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf new file mode 100644 index 0000000000000000000000000000000000000000..f522294ff0f3f8c52dfdaef7ebfaa06ebfcfaabf Binary files /dev/null and b/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf differ diff --git a/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf b/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf new file mode 100644 index 0000000000000000000000000000000000000000..4e98259c3b54076d684bf3459baeaeae8dbce97a Binary files /dev/null and b/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf differ diff --git a/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff b/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff new file mode 100644 index 0000000000000000000000000000000000000000..e7730f66275c87c28f26530d89264cffecf90be0 Binary files /dev/null and b/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff differ diff --git a/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 b/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..395f28beac23c7b0f7f3a1e714bd8dac253dd3bc Binary files /dev/null and b/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 differ diff --git a/assets/KaTeX_Fraktur-Regular-CB_wures.ttf b/assets/KaTeX_Fraktur-Regular-CB_wures.ttf new file mode 100644 index 0000000000000000000000000000000000000000..b8461b275fae76efd0d21fd0f1aaa696a5b10f9a Binary files /dev/null and b/assets/KaTeX_Fraktur-Regular-CB_wures.ttf differ diff --git a/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 b/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..735f6948d63c8cc7f8233735bb9c8d843c83d804 Binary files /dev/null and b/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 differ diff --git a/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff b/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff new file mode 100644 index 0000000000000000000000000000000000000000..acab069f90b6fe6301a004e6f8beaf6a0db48bce Binary files /dev/null and b/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff differ diff --git a/assets/KaTeX_Main-Bold-Cx986IdX.woff2 b/assets/KaTeX_Main-Bold-Cx986IdX.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..ab2ad21da6fbe6c171bb869240954d0ead8f68fd Binary files /dev/null and b/assets/KaTeX_Main-Bold-Cx986IdX.woff2 differ diff --git a/assets/KaTeX_Main-Bold-Jm3AIy58.woff b/assets/KaTeX_Main-Bold-Jm3AIy58.woff new file mode 100644 index 0000000000000000000000000000000000000000..f38136ac1cc2dcdc9d9b10b8521487468b1f768c Binary files /dev/null and b/assets/KaTeX_Main-Bold-Jm3AIy58.woff differ diff --git a/assets/KaTeX_Main-Bold-waoOVXN0.ttf b/assets/KaTeX_Main-Bold-waoOVXN0.ttf new file mode 100644 index 0000000000000000000000000000000000000000..4060e627dc341c1854260cbc3f7386e222a4d297 Binary files /dev/null and b/assets/KaTeX_Main-Bold-waoOVXN0.ttf differ diff --git a/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 b/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..5931794de4a2a485fa70099bf2659b145976d043 Binary files /dev/null and b/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 differ diff --git a/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf b/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf new file mode 100644 index 0000000000000000000000000000000000000000..dc007977ee709a236d9e82719cf7d4e5577a81b9 Binary files /dev/null and b/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf differ diff --git a/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff b/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff new file mode 100644 index 0000000000000000000000000000000000000000..67807b0bd4f867853271f5917fb3adf377f93f53 Binary files /dev/null and b/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff differ diff --git a/assets/KaTeX_Main-Italic-3WenGoN9.ttf b/assets/KaTeX_Main-Italic-3WenGoN9.ttf new file mode 100644 index 0000000000000000000000000000000000000000..0e9b0f354ad460202bba554359f5adcc8da666b7 Binary files /dev/null and b/assets/KaTeX_Main-Italic-3WenGoN9.ttf differ diff --git a/assets/KaTeX_Main-Italic-BMLOBm91.woff b/assets/KaTeX_Main-Italic-BMLOBm91.woff new file mode 100644 index 0000000000000000000000000000000000000000..6f43b594b6c1d863a0e3f93b001f8dd503316464 Binary files /dev/null and b/assets/KaTeX_Main-Italic-BMLOBm91.woff differ diff --git a/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 b/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..b50920e138807f385d0b0359f4f0f09891f18406 Binary files /dev/null and b/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 differ diff --git a/assets/KaTeX_Main-Regular-B22Nviop.woff2 b/assets/KaTeX_Main-Regular-B22Nviop.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..eb24a7ba282b03d830fa6c63ee897d92a5188736 Binary files /dev/null and b/assets/KaTeX_Main-Regular-B22Nviop.woff2 differ diff --git a/assets/KaTeX_Main-Regular-Dr94JaBh.woff b/assets/KaTeX_Main-Regular-Dr94JaBh.woff new file mode 100644 index 0000000000000000000000000000000000000000..21f5812968c42392a3eaea9b0c6320870b6b8b38 Binary files /dev/null and b/assets/KaTeX_Main-Regular-Dr94JaBh.woff differ diff --git a/assets/KaTeX_Main-Regular-ypZvNtVU.ttf b/assets/KaTeX_Main-Regular-ypZvNtVU.ttf new file mode 100644 index 0000000000000000000000000000000000000000..dd45e1ed2e18b32c516d9b481ebed3cb8bffa711 Binary files /dev/null and b/assets/KaTeX_Main-Regular-ypZvNtVU.ttf differ diff --git a/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf b/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf new file mode 100644 index 0000000000000000000000000000000000000000..728ce7a1e2cb689df32c3a6c26e1bd072dcf2acb Binary files /dev/null and b/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf differ diff --git a/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 b/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..29657023adc09956249f6295746c8ce4469b50d3 Binary files /dev/null and b/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 differ diff --git a/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff b/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff new file mode 100644 index 0000000000000000000000000000000000000000..0ae390d74c9f665cf8b1e5ea5483395da7513444 Binary files /dev/null and b/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff differ diff --git a/assets/KaTeX_Math-Italic-DA0__PXp.woff b/assets/KaTeX_Math-Italic-DA0__PXp.woff new file mode 100644 index 0000000000000000000000000000000000000000..eb5159d4c1ca83fb92b3190223698427df0e010c Binary files /dev/null and b/assets/KaTeX_Math-Italic-DA0__PXp.woff differ diff --git a/assets/KaTeX_Math-Italic-flOr_0UB.ttf b/assets/KaTeX_Math-Italic-flOr_0UB.ttf new file mode 100644 index 0000000000000000000000000000000000000000..70d559b4e937ca1b805eb39f544cbebe3c58ca6f Binary files /dev/null and b/assets/KaTeX_Math-Italic-flOr_0UB.ttf differ diff --git a/assets/KaTeX_Math-Italic-t53AETM-.woff2 b/assets/KaTeX_Math-Italic-t53AETM-.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..215c143fd7805a5c2b222bd7892a1a2b09610020 Binary files /dev/null and b/assets/KaTeX_Math-Italic-t53AETM-.woff2 differ diff --git a/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf b/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf new file mode 100644 index 0000000000000000000000000000000000000000..2f65a8a3a6d3628d11ea9c26c9077cef672fe427 Binary files /dev/null and b/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf differ diff --git a/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 b/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..cfaa3bda59246b49e94298478d6de3b3208066c8 Binary files /dev/null and b/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 differ diff --git a/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff b/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff new file mode 100644 index 0000000000000000000000000000000000000000..8d47c02d9408d34b2a9d566c0fe0d42bf82fb735 Binary files /dev/null and b/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff differ diff --git a/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 b/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..349c06dc609f896392fd5bc8b364d3bc3efc9330 Binary files /dev/null and b/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 differ diff --git a/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff b/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff new file mode 100644 index 0000000000000000000000000000000000000000..7e02df963621a5e26d53d510f0b4992eebde1c60 Binary files /dev/null and b/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff differ diff --git a/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf b/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf new file mode 100644 index 0000000000000000000000000000000000000000..d5850df98ec19de2eee9ff922ef59586efe471d0 Binary files /dev/null and b/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf differ diff --git a/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf b/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf new file mode 100644 index 0000000000000000000000000000000000000000..537279f6bd2184ed32f1a5168850609147d58ee6 Binary files /dev/null and b/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf differ diff --git a/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff b/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff new file mode 100644 index 0000000000000000000000000000000000000000..31b84829b42edae20d0148eeec0d922dad2108c4 Binary files /dev/null and b/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff differ diff --git a/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 b/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..a90eea85f6f7bded69ff5d40114447a6d8b48cfe Binary files /dev/null and b/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 differ diff --git a/assets/KaTeX_Script-Regular-C5JkGWo-.ttf b/assets/KaTeX_Script-Regular-C5JkGWo-.ttf new file mode 100644 index 0000000000000000000000000000000000000000..fd679bf374af72f2a183b97b40c9c7e9e51fbe5e Binary files /dev/null and b/assets/KaTeX_Script-Regular-C5JkGWo-.ttf differ diff --git a/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 b/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..b3048fc115681ee6c1bc86b0aa158cfbbf59daa3 Binary files /dev/null and b/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 differ diff --git a/assets/KaTeX_Script-Regular-D5yQViql.woff b/assets/KaTeX_Script-Regular-D5yQViql.woff new file mode 100644 index 0000000000000000000000000000000000000000..0e7da821eee0dd05a0a6f0b16c2c1345dc573a84 Binary files /dev/null and b/assets/KaTeX_Script-Regular-D5yQViql.woff differ diff --git a/assets/KaTeX_Size1-Regular-C195tn64.woff b/assets/KaTeX_Size1-Regular-C195tn64.woff new file mode 100644 index 0000000000000000000000000000000000000000..7f292d91184f257054ef77cc1cd3443db757c9cc Binary files /dev/null and b/assets/KaTeX_Size1-Regular-C195tn64.woff differ diff --git a/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf b/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf new file mode 100644 index 0000000000000000000000000000000000000000..871fd7d19d8658f64d8696ed9cdfc82c821ed76d Binary files /dev/null and b/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf differ diff --git a/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 b/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..c5a8462fbfe2c39a7c1857b9e296e62500a8a8a5 Binary files /dev/null and b/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 differ diff --git a/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf b/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf new file mode 100644 index 0000000000000000000000000000000000000000..7a212caf91c0007e826fee2d622bf48acbd30dde Binary files /dev/null and b/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf differ diff --git a/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 b/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..e1bccfe2403a4ed770c1697ae7c15b9e1cd9bc4e Binary files /dev/null and b/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 differ diff --git a/assets/KaTeX_Size2-Regular-oD1tc_U0.woff b/assets/KaTeX_Size2-Regular-oD1tc_U0.woff new file mode 100644 index 0000000000000000000000000000000000000000..d241d9be2d317f7b39b401d96c8b18836acea0fa Binary files /dev/null and b/assets/KaTeX_Size2-Regular-oD1tc_U0.woff differ diff --git a/assets/KaTeX_Size3-Regular-CTq5MqoE.woff b/assets/KaTeX_Size3-Regular-CTq5MqoE.woff new file mode 100644 index 0000000000000000000000000000000000000000..e6e9b658dcf1cd031ac82b6b8f312444c55d4fc0 Binary files /dev/null and b/assets/KaTeX_Size3-Regular-CTq5MqoE.woff differ diff --git a/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf b/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf new file mode 100644 index 0000000000000000000000000000000000000000..00bff3495fa9d2f98c1c9ce436add6a1bcfe87fb Binary files /dev/null and b/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf differ diff --git a/assets/KaTeX_Size4-Regular-BF-4gkZK.woff b/assets/KaTeX_Size4-Regular-BF-4gkZK.woff new file mode 100644 index 0000000000000000000000000000000000000000..e1ec5457664f438ce5a1cc6dd8409bf60ca7804b Binary files /dev/null and b/assets/KaTeX_Size4-Regular-BF-4gkZK.woff differ diff --git a/assets/KaTeX_Size4-Regular-DWFBv043.ttf b/assets/KaTeX_Size4-Regular-DWFBv043.ttf new file mode 100644 index 0000000000000000000000000000000000000000..74f08921f00f71f413ca42c9d1c90202e672ef38 Binary files /dev/null and b/assets/KaTeX_Size4-Regular-DWFBv043.ttf differ diff --git a/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 b/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..680c13085076a2f6c5a7e695935ec3f21cddb65f Binary files /dev/null and b/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 differ diff --git a/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff b/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff new file mode 100644 index 0000000000000000000000000000000000000000..2432419f28936aff53ddfa2a732d027e6a6648fd Binary files /dev/null and b/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff differ diff --git a/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 b/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..771f1af705f5cef5f578b3a1e7d8eff66f9b76b0 Binary files /dev/null and b/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 differ diff --git a/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf b/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf new file mode 100644 index 0000000000000000000000000000000000000000..c83252c5714c71a3e0ec62195884167339a0129b Binary files /dev/null and b/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf differ diff --git a/assets/index-D3g1yBS0.js b/assets/index-D3g1yBS0.js new file mode 100644 index 0000000000000000000000000000000000000000..a685ac01d5690e7e75e4233436ea6a63162e5e75 --- /dev/null +++ b/assets/index-D3g1yBS0.js @@ -0,0 +1,31697 @@ +function vR(n,e){for(var t=0;ts[r]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&s(o)}).observe(document,{childList:!0,subtree:!0});function t(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function s(r){if(r.ep)return;r.ep=!0;const i=t(r);fetch(r.href,i)}})();/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bR=1e-7,yR=1e-4;class t2{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class b0{refCount(e){return lr("refCount")}incRef(e){return lr("incRef")}timerAvailable(){return!0}time(e){return lr("time")}read(e){return lr("read")}readSync(e){return lr("readSync")}readToGPU(e,t){return lr("readToGPU")}numDataIds(){return lr("numDataIds")}disposeData(e,t){return lr("disposeData")}write(e,t,s){return lr("write")}move(e,t,s,r,i){return lr("move")}createTensorFromGPUData(e,t,s){return lr("createTensorFromGPUData")}memory(){return lr("memory")}floatPrecision(){return lr("floatPrecision")}epsilon(){return this.floatPrecision()===32?bR:yR}dispose(){return lr("dispose")}}function lr(n){throw new Error(`'${n}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wR(n){let e=n.length,t=0;for(;e>0;)t=Math.random()*e|0,e--,fc(n,e,t)}function n2(n,e,t){return Math.max(n,Math.min(e,t))}function s2(n){return n%2===0?n:n+1}function fc(n,e,t){const s=n[e];n[e]=n[t],n[t]=s}function qS(n){let e=0;for(let t=0;tt+` Shapes ${n} and ${e} must match`)}function XS(n){N(n!=null,()=>"The input to the tensor constructor must be a non-null value.")}function re(n){if(n.length===0)return 1;let e=n[0];for(let t=1;t0,t,s){return new Promise((r,i)=>{let o=0;const a=()=>{if(n()){r();return}o++;const l=e(o);if(t!=null&&o>=t){i();return}s!=null?s(a,l):setTimeout(a,l)};a()})}function r2(n,e){let t=1,s=-1;for(let i=0;i=0)t*=n[i];else if(n[i]===-1){if(s!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${i}`);s=i}else if(n[i]<0)throw Error(`Shapes can not be < 0. Found ${n[i]} at dim ${i}`);if(s===-1){if(e>0&&e!==t)throw Error(`Size(${e}) must match the product of shape ${n}`);return n}if(t===0)throw Error(`Cannot infer the missing size in [${n}] when there are 0 elements`);if(e%t!==0)throw Error(`The implicit shape can't be a fractional number. Got ${e} / ${t}`);const r=n.slice();return r[s]=e/t,r}function It(n,e){const t=e.length;return n=n==null?e.map((s,r)=>r):[].concat(n),N(n.every(s=>s>=-t&&s`All values in axis param must be in range [-${t}, ${t}) but got axis ${n}`),N(n.every(s=>kc(s)),()=>`All values in axis param must be integers but got axis ${n}`),n.map(s=>s<0?t+s:s)}function ba(n,e){const t=[],s=[],r=e!=null&&Array.isArray(e)&&e.length===0,i=e==null||r?null:It(e,n).sort();let o=0;for(let a=0;aa)&&n[a]===1&&(t.push(n[a]),s.push(a)),i[o]<=a&&o++}n[a]!==1&&(t.push(n[a]),s.push(a))}return{newShape:t,keptDims:s}}function hs(n,e){return Pn(n,e)}function Pn(n,e){let t=null;if(n==null||n==="float32")t=new Float32Array(e);else if(n==="int32")t=new Int32Array(e);else if(n==="bool")t=new Uint8Array(e);else if(n==="string")t=new Array(e);else throw new Error(`Unknown data type ${n}`);return t}function SR(n,e){for(let t=0;te+=t.length),e}function Kc(n){return typeof n=="string"||n instanceof String}function TR(n){return typeof n=="boolean"}function H1(n){return typeof n=="number"}function Il(n){return Array.isArray(n)?Il(n[0]):n instanceof Float32Array?"float32":n instanceof Int32Array||n instanceof Uint8Array||n instanceof Uint8ClampedArray?"int32":H1(n)?"float32":Kc(n)?"string":TR(n)?"bool":"float32"}function q1(n){return!!(n&&n.constructor&&n.call&&n.apply)}function X1(n,e){for(let t=e;t=0;--s)t[s]=t[s+1]*n[s+1];return t}function KS(n,e,t,s=!1){const r=new Array;if(e.length===1){const i=e[0]*(s?2:1);for(let o=0;ol*c)*(s?2:1);for(let l=0;lr*i)*(t?2:1);if(s===0)return[];if(s!==e.length)throw new Error(`[${n}] does not match the input size ${e.length}${t?" for a complex tensor":""}.`);return KS(0,n,e,t)}function Sf(n,e){if(Array.isArray(n))return n;if(e==="float32")return n instanceof Float32Array?n:new Float32Array(n);if(e==="int32")return n instanceof Int32Array?n:new Int32Array(n);if(e==="bool"||e==="string")return Uint8Array.from(new Int32Array(n));throw new Error(`Unknown dtype ${e}`)}function o2(n,e){const t=Cs(n,e);for(let s=0;ss*r,1);if(e==null||e==="float32")return yi(n,new Float32Array(t));if(e==="int32")return yi(n,new Int32Array(t));if(e==="bool")return yi(n,new Uint8Array(t));throw new Error(`Unknown data type ${e}`)}function No(n){n.forEach(e=>{N(Number.isInteger(e)&&e>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${n}].`)})}function Gi(n,e,t){if(e===0)return 0;if(e===1)return n[0];let s=n[n.length-1];for(let r=0;r"u"||typeof this.global.location>"u"||typeof this.global.location.search>"u")return;const e=this.getQueryParams(this.global.location.search);Fb in e&&e[Fb].split(",").forEach(s=>{const[r,i]=s.split(":");this.urlFlags[r]=AR(r,i)})}}function ER(n){const e={};return n.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(t,...s)=>(kR(e,s[0],s[1]),s.join("="))),e}function kR(n,e,t){n[decodeURIComponent(e)]=decodeURIComponent(t||"")}function AR(n,e){const t=e.toLowerCase();return t==="true"||t==="false"?t==="true":`${+t}`===t?+t:e}function oe(){return YS}let YS=null;function RR(n){YS=n}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Ig;function ZS(){if(Ig==null){let n;if(typeof window<"u")n=window;else if(typeof global<"u")n=global;else if(typeof process<"u")n=process;else if(typeof self<"u")n=self;else throw new Error("Could not find a global object");Ig=n}return Ig}function MR(){const n=ZS();return n._tfGlobals==null&&(n._tfGlobals=new Map),n._tfGlobals}function l2(n,e){const t=MR();if(t.has(n))return t.get(n);{const s=e();return t.set(n,s),t.get(n)}}const td="Abs",Yc="Acos",Zc="Acosh",El="Add",w0="AddN",S0="All",C0="Any",nd="ArgMax",sd="ArgMin",Jc="Asin",Qc="Asinh",eu="Atan",tu="Atanh",nu="Atan2",rd="AvgPool",_0="AvgPoolGrad",id="AvgPool3D",T0="AvgPool3DGrad",od="BatchMatMul",ad="BatchToSpaceND",I0="Bincount",c2="BitwiseAnd",NR="BroadcastTo",u2="BroadcastArgs",su="Cast",ru="Ceil",iu="ClipByValue",E0="Complex",ld="ComplexAbs",cd="Concat",ud="Conv2D",k0="Conv2DBackpropFilter",hd="Conv2DBackpropInput",dd="Conv3D",A0="Conv3DBackpropFilterV2",R0="Conv3DBackpropInputV2",ou="Cos",au="Cosh",M0="Cumprod",pd="Cumsum",N0="CropAndResize",$0="DenseBincount",D0="DepthToSpace",fd="DepthwiseConv2dNative",P0="DepthwiseConv2dNativeBackpropFilter",L0="DepthwiseConv2dNativeBackpropInput",h2="Diag",md="Dilation2D",Rf="Dilation2DBackpropInput",Mf="Dilation2DBackpropFilter",JS="Draw",lu="RealDiv",F0="Einsum",cu="Elu",O0="EluGrad",uu="Erf",gd="Equal",hu="Exp",xd="ExpandDims",du="Expm1",z0="FFT",B0="Fill",U0="FlipLeftRight",pu="Floor",fu="FloorDiv",vd="FusedBatchNorm",bd="GatherV2",d2="GatherNd",yd="Greater",mu="GreaterEqual",gu="Identity",V0="IFFT",W0="Imag",xu="IsFinite",vu="IsInf",bu="IsNan",wd="LeakyRelu",Sd="Less",Cd="LessEqual",p2="LinSpace",yu="Log",wu="Log1p",_d="LogicalAnd",Td="LogicalNot",Id="LogicalOr",$R="LogSoftmax",Ed="LRN",G0="LRNGrad",kd="Max",Su="Maximum",Ad="MaxPool",H0="MaxPoolGrad",Rd="MaxPool3D",q0="MaxPool3DGrad",f2="MaxPoolWithArgmax",Md="Mean",Nd="Min",Cu="Minimum",$d="MirrorPad",_u="Mod",m2="Multinomial",Tu="Multiply",Dd="Neg",Pd="NotEqual",X0="NonMaxSuppressionV3",g2="NonMaxSuppressionV4",K0="NonMaxSuppressionV5",Ld="OnesLike",Fd="OneHot",Od="Pack",zd="PadV2",Iu="Pow",Bd="Prelu",Ud="Prod",QS="RaggedGather",eC="RaggedRange",tC="RaggedTensorToTensor",j0="Range",Y0="Real",Eu="Reciprocal",ku="Relu",Vd="Reshape",Wd="ResizeNearestNeighbor",Z0="ResizeNearestNeighborGrad",Gd="ResizeBilinear",J0="ResizeBilinearGrad",Au="Relu6",Hd="Reverse",Ru="Round",Mu="Rsqrt",x2="ScatterNd",v2="TensorScatterUpdate",b2="SearchSorted",qd="Select",Nu="Selu",Xd="Slice",$u="Sin",Du="Sinh",Pu="Sign",Lu="Sigmoid",Fu="Softplus",Ou="Sqrt",Kd="Sum",jd="SpaceToBatchND",Yd="SplitV",Zd="Softmax",nC="SparseFillEmptyRows",sC="SparseReshape",y2="SparseSegmentMean",w2="SparseSegmentSum",S2="SparseToDense",zu="SquaredDifference",Q0="Square",C2="StaticRegexReplace",em="StridedSlice",_2="StringNGrams",rC="StringSplit",iC="StringToHashBucketFast",Bu="Sub",Uu="Tan",Vu="Tanh",Wu="Tile",tm="TopK",nm="Transform",rl="Transpose",T2="Unique",Jd="Unpack",Qd="UnsortedSegmentSum",ep="ZerosLike",Gu="Step",oC="FromPixels",sm="RotateWithOffset",Ph="_FusedMatMul",Lh="FusedConv2D",I2="FusedDepthwiseConv2D";/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ir(...n){oe().getBool("IS_TEST")||oe().getBool("PROD")||console.warn(...n)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Nf=l2("kernelRegistry",()=>new Map),K1=l2("gradRegistry",()=>new Map);function Ob(n,e){const t=aC(n,e);return Nf.get(t)}function zb(n){return K1.get(n)}function Bb(n){const e=Nf.entries(),t=[];for(;;){const{done:s,value:r}=e.next();if(s)break;const[i,o]=r,[a]=i.split("_");a===n&&t.push(o)}return t}function E2(n){const{kernelName:e,backendName:t}=n,s=aC(e,t);Nf.has(s)&&Ir(`The kernel '${e}' for backend '${t}' is already registered`),Nf.set(s,n)}function DR(n){const{kernelName:e}=n;K1.has(e)&&oe().getBool("DEBUG")&&Ir(`Overriding the gradient for '${e}'`),K1.set(e,n)}function aC(n,e){return`${e}_${n}`}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lC(n){return n instanceof Float32Array||n instanceof Int32Array||n instanceof Uint8Array||n instanceof Uint8ClampedArray}var kl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function PR(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function LR(n){if(n.__esModule)return n;var e=n.default;if(typeof e=="function"){var t=function s(){return this instanceof s?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(s){var r=Object.getOwnPropertyDescriptor(n,s);Object.defineProperty(t,s,r.get?r:{enumerable:!0,get:function(){return n[s]}})}),t}var cC=wn,Xr=null;try{Xr=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function wn(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}wn.prototype.__isLong__;Object.defineProperty(wn.prototype,"__isLong__",{value:!0});function yr(n){return(n&&n.__isLong__)===!0}wn.isLong=yr;var Ub={},Vb={};function Al(n,e){var t,s,r;return e?(n>>>=0,(r=0<=n&&n<256)&&(s=Vb[n],s)?s:(t=Sn(n,(n|0)<0?-1:0,!0),r&&(Vb[n]=t),t)):(n|=0,(r=-128<=n&&n<128)&&(s=Ub[n],s)?s:(t=Sn(n,n<0?-1:0,!1),r&&(Ub[n]=t),t))}wn.fromInt=Al;function Kr(n,e){if(isNaN(n))return e?Qa:jr;if(e){if(n<0)return Qa;if(n>=uC)return pC}else{if(n<=-Gb)return fr;if(n+1>=Gb)return dC}return n<0?Kr(-n,e).neg():Sn(n%Ac|0,n/Ac|0,e)}wn.fromNumber=Kr;function Sn(n,e,t){return new wn(n,e,t)}wn.fromBits=Sn;var $f=Math.pow;function k2(n,e,t){if(n.length===0)throw Error("empty string");if(n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return jr;if(typeof e=="number"?(t=e,e=!1):e=!!e,t=t||10,t<2||360)throw Error("interior hyphen");if(s===0)return k2(n.substring(1),e,t).neg();for(var r=Kr($f(t,8)),i=jr,o=0;o>>0:this.low};Ue.toNumber=function(){return this.unsigned?(this.high>>>0)*Ac+(this.low>>>0):this.high*Ac+(this.low>>>0)};Ue.toString=function(e){if(e=e||10,e<2||36>>0,u=c.toString(e);if(o=l,o.isZero())return u+a;for(;u.length<6;)u="0"+u;a=""+u+a}};Ue.getHighBits=function(){return this.high};Ue.getHighBitsUnsigned=function(){return this.high>>>0};Ue.getLowBits=function(){return this.low};Ue.getLowBitsUnsigned=function(){return this.low>>>0};Ue.getNumBitsAbs=function(){if(this.isNegative())return this.eq(fr)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};Ue.isOdd=function(){return(this.low&1)===1};Ue.isEven=function(){return(this.low&1)===0};Ue.equals=function(e){return yr(e)||(e=Ai(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};Ue.eq=Ue.equals;Ue.notEquals=function(e){return!this.eq(e)};Ue.neq=Ue.notEquals;Ue.ne=Ue.notEquals;Ue.lessThan=function(e){return this.comp(e)<0};Ue.lt=Ue.lessThan;Ue.lessThanOrEqual=function(e){return this.comp(e)<=0};Ue.lte=Ue.lessThanOrEqual;Ue.le=Ue.lessThanOrEqual;Ue.greaterThan=function(e){return this.comp(e)>0};Ue.gt=Ue.greaterThan;Ue.greaterThanOrEqual=function(e){return this.comp(e)>=0};Ue.gte=Ue.greaterThanOrEqual;Ue.ge=Ue.greaterThanOrEqual;Ue.compare=function(e){if(yr(e)||(e=Ai(e)),this.eq(e))return 0;var t=this.isNegative(),s=e.isNegative();return t&&!s?-1:!t&&s?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};Ue.comp=Ue.compare;Ue.negate=function(){return!this.unsigned&&this.eq(fr)?fr:this.not().add(xc)};Ue.neg=Ue.negate;Ue.add=function(e){yr(e)||(e=Ai(e));var t=this.high>>>16,s=this.high&65535,r=this.low>>>16,i=this.low&65535,o=e.high>>>16,a=e.high&65535,l=e.low>>>16,c=e.low&65535,u=0,h=0,d=0,p=0;return p+=i+c,d+=p>>>16,p&=65535,d+=r+l,h+=d>>>16,d&=65535,h+=s+a,u+=h>>>16,h&=65535,u+=t+o,u&=65535,Sn(d<<16|p,u<<16|h,this.unsigned)};Ue.subtract=function(e){return yr(e)||(e=Ai(e)),this.add(e.neg())};Ue.sub=Ue.subtract;Ue.multiply=function(e){if(this.isZero())return jr;if(yr(e)||(e=Ai(e)),Xr){var t=Xr.mul(this.low,this.high,e.low,e.high);return Sn(t,Xr.get_high(),this.unsigned)}if(e.isZero())return jr;if(this.eq(fr))return e.isOdd()?fr:jr;if(e.eq(fr))return this.isOdd()?fr:jr;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Hb)&&e.lt(Hb))return Kr(this.toNumber()*e.toNumber(),this.unsigned);var s=this.high>>>16,r=this.high&65535,i=this.low>>>16,o=this.low&65535,a=e.high>>>16,l=e.high&65535,c=e.low>>>16,u=e.low&65535,h=0,d=0,p=0,f=0;return f+=o*u,p+=f>>>16,f&=65535,p+=i*u,d+=p>>>16,p&=65535,p+=o*c,d+=p>>>16,p&=65535,d+=r*u,h+=d>>>16,d&=65535,d+=i*c,h+=d>>>16,d&=65535,d+=o*l,h+=d>>>16,d&=65535,h+=s*u+r*c+i*l+o*a,h&=65535,Sn(p<<16|f,h<<16|d,this.unsigned)};Ue.mul=Ue.multiply;Ue.divide=function(e){if(yr(e)||(e=Ai(e)),e.isZero())throw Error("division by zero");if(Xr){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?Xr.div_u:Xr.div_s)(this.low,this.high,e.low,e.high);return Sn(t,Xr.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Qa:jr;var s,r,i;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Qa;if(e.gt(this.shru(1)))return hC;i=Qa}else{if(this.eq(fr)){if(e.eq(xc)||e.eq(j1))return fr;if(e.eq(fr))return xc;var o=this.shr(1);return s=o.div(e).shl(1),s.eq(jr)?e.isNegative()?xc:j1:(r=this.sub(e.mul(s)),i=s.add(r.div(e)),i)}else if(e.eq(fr))return this.unsigned?Qa:jr;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();i=jr}for(r=this;r.gte(e);){s=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(s)/Math.LN2),l=a<=48?1:$f(2,a-48),c=Kr(s),u=c.mul(e);u.isNegative()||u.gt(r);)s-=l,c=Kr(s,this.unsigned),u=c.mul(e);c.isZero()&&(c=xc),i=i.add(c),r=r.sub(u)}return i};Ue.div=Ue.divide;Ue.modulo=function(e){if(yr(e)||(e=Ai(e)),Xr){var t=(this.unsigned?Xr.rem_u:Xr.rem_s)(this.low,this.high,e.low,e.high);return Sn(t,Xr.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};Ue.mod=Ue.modulo;Ue.rem=Ue.modulo;Ue.not=function(){return Sn(~this.low,~this.high,this.unsigned)};Ue.and=function(e){return yr(e)||(e=Ai(e)),Sn(this.low&e.low,this.high&e.high,this.unsigned)};Ue.or=function(e){return yr(e)||(e=Ai(e)),Sn(this.low|e.low,this.high|e.high,this.unsigned)};Ue.xor=function(e){return yr(e)||(e=Ai(e)),Sn(this.low^e.low,this.high^e.high,this.unsigned)};Ue.shiftLeft=function(e){return yr(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Sn(this.low<>>32-e,this.unsigned):Sn(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):Sn(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};Ue.shr=Ue.shiftRight;Ue.shiftRightUnsigned=function(e){if(yr(e)&&(e=e.toInt()),e&=63,e===0)return this;var t=this.high;if(e<32){var s=this.low;return Sn(s>>>e|t<<32-e,t>>>e,this.unsigned)}else return e===32?Sn(t,0,this.unsigned):Sn(t>>>e-32,0,this.unsigned)};Ue.shru=Ue.shiftRightUnsigned;Ue.shr_u=Ue.shiftRightUnsigned;Ue.toSigned=function(){return this.unsigned?Sn(this.low,this.high,!1):this};Ue.toUnsigned=function(){return this.unsigned?this:Sn(this.low,this.high,!0)};Ue.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};Ue.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};Ue.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};wn.fromBytes=function(e,t,s){return s?wn.fromBytesLE(e,t):wn.fromBytesBE(e,t)};wn.fromBytesLE=function(e,t){return new wn(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};wn.fromBytesBE=function(e,t){return new wn(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};const fC=PR(cC),OR=vR({__proto__:null,default:fC},[cC]);/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Xa=fC||OR;function rm(n){return Xa.fromString(n,!0,16)}const mC=rm("c3a5c85c97cb3127"),Va=rm("b492b66fbe98f273"),Fs=rm("9ae16a3b2f90404f");function Y1(n){return n.xor(n.shru(47))}function gC(n,e,t){const s=n.slice(e,e+t);return Xa.fromBytes(Array.from(s),!0,!0)}function pn(n,e){return gC(n,e,8)}function qb(n,e){return gC(n,e,4)}function cs(n,e){return e===0?n:n.shru(e).or(n.shl(64-e))}function ea(n,e,t=rm("9ddfea08eb382d69")){let s=n.xor(e).mul(t);s=s.xor(s.shru(47));let r=e.xor(s).mul(t);return r=r.xor(r.shru(47)),r=r.mul(t),r}function zR(n,e,t,s,r,i){r=r.add(n),i=cs(i.add(r).add(s),21);const o=r;return r=r.add(e),r=r.add(t),i=i.add(cs(r,44)),[r.add(s),i.add(o)]}function Mp(n,e,t,s){return zR(pn(n,e),pn(n,e+8),pn(n,e+16),pn(n,e+24),t,s)}function BR(n,e=n.length){if(e>=8){const t=Fs.add(e*2),s=pn(n,0).add(Fs),r=pn(n,e-8),i=cs(r,37).mul(t).add(s),o=cs(s,25).add(r).mul(t);return ea(i,o,t)}if(e>=4){const t=Fs.add(e*2),s=qb(n,0);return ea(s.shl(3).add(e),qb(n,e-4),t)}if(e>0){const t=n[0],s=n[e>>1],r=n[e-1],i=t+(s<<8),o=e+(r<<2);return Y1(Fs.mul(i).xor(mC.mul(o))).mul(Fs)}return Fs}function UR(n,e=n.length){const t=Fs.add(e*2),s=pn(n,0).mul(Va),r=pn(n,8),i=pn(n,e-8).mul(t),o=pn(n,e-16).mul(Fs);return ea(cs(s.add(r),43).add(cs(i,30)).add(o),s.add(cs(r.add(Fs),18)).add(i),t)}function VR(n,e=n.length){const t=Fs.add(e*2),s=pn(n,0).mul(Fs),r=pn(n,8),i=pn(n,e-8).mul(t),o=pn(n,e-16).mul(Fs),a=cs(s.add(r),43).add(cs(i,30)).add(o),l=ea(a,s.add(cs(r.add(Fs),18)).add(i),t),c=pn(n,16).mul(t),u=pn(n,24),h=a.add(pn(n,e-32)).mul(t),d=l.add(pn(n,e-24)).mul(t);return ea(cs(c.add(u),43).add(cs(h,30)).add(d),c.add(cs(u.add(s),18)).add(h),t)}function WR(n,e=n.length){const t=Xa.fromNumber(81,!0);if(e<=32)return e<=16?BR(n,e):UR(n,e);if(e<=64)return VR(n,e);let s=t,r=t.mul(Va).add(113),i=Y1(r.mul(Fs).add(113)).mul(Fs),o=[Xa.UZERO,Xa.UZERO],a=[Xa.UZERO,Xa.UZERO];s=s.mul(Fs).add(pn(n,0));let l=0;const c=(e-1>>6)*64,u=c+(e-1&63)-63;do s=cs(s.add(r).add(o[0]).add(pn(n,l+8)),37).mul(Va),r=cs(r.add(o[1]).add(pn(n,l+48)),42).mul(Va),s=s.xor(a[1]),r=r.add(o[0]).add(pn(n,l+40)),i=cs(i.add(a[0]),33).mul(Va),o=Mp(n,l,o[1].mul(Va),s.add(a[0])),a=Mp(n,l+32,i.add(a[1]),r.add(pn(n,l+16))),[i,s]=[s,i],l+=64;while(l!==c);const h=Va.add(i.and(255).shl(1));return l=u,a[0]=a[0].add(e-1&63),o[0]=o[0].add(a[0]),a[0]=a[0].add(o[0]),s=cs(s.add(r).add(o[0]).add(pn(n,l+8)),37).mul(h),r=cs(r.add(o[1]).add(pn(n,l+48)),42).mul(h),s=s.xor(a[1].mul(9)),r=r.add(o[0].mul(9).add(pn(n,l+40))),i=cs(i.add(a[0]),33).mul(h),o=Mp(n,l,o[1].mul(h),s.add(a[0])),a=Mp(n,l+32,i.add(a[1]),r.add(pn(n,l+16))),[i,s]=[s,i],ea(ea(o[0],a[0],h).add(Y1(r).mul(mC)).add(i),ea(o[1],a[1],h).add(s),h)}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ya(n,e){return e==="string"?_o(n):Rl([n],e)}function GR(n,e){return n instanceof Float32Array&&e==="float32"||n instanceof Int32Array&&e==="int32"||n instanceof Uint8Array&&e==="bool"}function Rl(n,e){if(e==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(n)&&(n=ko(n)),oe().getBool("DEBUG")&&SR(n,e),GR(n,e))return n;if(e==null||e==="float32"||e==="complex64")return new Float32Array(n);if(e==="int32")return new Int32Array(n);if(e==="bool"){const t=new Uint8Array(n.length);for(let s=0;s{r=s()};let o;const a=qs();if(this.backendTimer.timerAvailable())o=this.backendTimer.time(i);else{i();for(const c of r)c.dataSync();o=Promise.resolve({kernelMs:qs()-a})}if(oe().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let c=0;c{qR(h,u.dtype,e)})}return{kernelName:e,outputs:r,inputs:t,timeMs:o.then(c=>c.kernelMs),extraInfo:o.then(c=>c.getExtraProfileInfo!=null?c.getExtraProfileInfo():"")}}logKernelProfile(e){const{kernelName:t,outputs:s,timeMs:r,inputs:i,extraInfo:o}=e;s.forEach(a=>{Promise.all([a.data(),r,o]).then(l=>{this.logger.logKernelProfile(t,a,l[0],l[1],i,l[2])})})}}function qR(n,e,t){if(e!=="float32")return!1;for(let s=0;s0?x:""} `}}console.log(`%c${l} %c${a} %c${c}D ${h} %c${u} %c${d} %c${o}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function KR(n,e,t){const s={},r={};for(let l=0;ls[x.id]=!0),p=!0,r[c.id]=!0;break}if(p)break}}const i={};i[t.id]=!0;const o={};for(let l=n.length-1;l>=0;l--){const c=n[l],u=c.inputs;for(let h=0;h=0;r--){const i=e[r],o=[];if(i.outputs.forEach(l=>{const c=n[l.id];c!=null?o.push(c):o.push(null)}),i.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${i.kernelName}.`);const a=i.gradient(o);for(const l in i.inputs){if(!(l in a))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(a)}.`);const c=t(()=>a[l]());if(c.dtype!=="float32")throw new Error(`Error in gradient for op ${i.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${c.dtype}'`);const u=i.inputs[l];if(!Wt(c.shape,u.shape))throw new Error(`Error in gradient for op ${i.kernelName}. The gradient of input '${l}' has shape '${c.shape}', which does not match the shape of the input '${u.shape}'`);if(n[u.id]==null)n[u.id]=c;else{const h=n[u.id];n[u.id]=s(h,c),h.dispose()}}}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Xb=20,ph=3,Eg=7;function YR(n,e,t,s){const r=it(e),i=ZR(n,e,t,r),o=e.length,a=Cf(n,e,t,r,i),l=["Tensor"];return s&&(l.push(` dtype: ${t}`),l.push(` rank: ${o}`),l.push(` shape: [${e}]`),l.push(" values:")),l.push(a.map(c=>" "+c).join(` +`)),l.join(` +`)}function ZR(n,e,t,s){const r=re(e),i=s[s.length-1],o=new Array(i).fill(0),a=e.length,l=t==="complex64"?_h(n):n;if(a>1)for(let c=0;cXb){const m=ph*o;let g=Array.from(n.slice(0,m)),v=Array.from(n.slice((a-ph)*o,a*o));return t==="complex64"&&(g=_h(g),v=_h(v)),["["+g.map((b,y)=>Ch(b,r[y],t)).join(", ")+", ..., "+v.map((b,y)=>Ch(b,r[a-ph+y],t)).join(", ")+"]"]}return["["+(t==="complex64"?_h(n):Array.from(n)).map((m,g)=>Ch(m,r[g],t)).join(", ")+"]"]}const c=e.slice(1),u=s.slice(1),h=s[0]*o,d=[];if(a>Xb){for(let x=0;x0?d[0]+p:"");for(let x=1;x`Length of values '${r}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")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=s||Pn(t,this.size),this.strides=it(e)}set(e,...t){t.length===0&&(t=[0]),N(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const s=this.locToIndex(t);this.values[s]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(const r of e){if(r<0||r>=this.shape[t]){const i=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(i)}t++}let s=e[e.length-1];for(let r=0;rCi(s))}catch{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(),hi().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=hi().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Ci(t))}catch{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 hi().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),hi().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return mc.print(this,e)}clone(){return this.throwIfDisposed(),mc.clone(this)}toString(e=!1){const t=this.dataSync();return YR(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),mc.cast(this,e)}variable(e=!0,t,s){return this.throwIfDisposed(),hi().makeVariable(this,e,t,s)}}Object.defineProperty(Yn,Symbol.hasInstance,{value:n=>!!n&&n.data!=null&&n.dataSync!=null&&n.throwIfDisposed!=null});function me(){return l2("Tensor",()=>Yn)}me();class Df extends Yn{constructor(e,t,s,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=s}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(!Wt(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);hi().disposeTensor(this),this.dataId=e.dataId,hi().incRef(this,null)}dispose(){hi().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Df,Symbol.hasInstance,{value:n=>n instanceof Yn&&n.assign!=null&&n.assign instanceof Function});/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Kb;(function(n){n.R0="R0",n.R1="R1",n.R2="R2",n.R3="R3",n.R4="R4",n.R5="R5",n.R6="R6"})(Kb||(Kb={}));var Z1;(function(n){n.float32="float32",n.int32="int32",n.bool="int32",n.complex64="complex64"})(Z1||(Z1={}));var J1;(function(n){n.float32="float32",n.int32="int32",n.bool="bool",n.complex64="complex64"})(J1||(J1={}));var Q1;(function(n){n.float32="float32",n.int32="float32",n.bool="float32",n.complex64="complex64"})(Q1||(Q1={}));var ex;(function(n){n.float32="complex64",n.int32="complex64",n.bool="complex64",n.complex64="complex64"})(ex||(ex={}));const eM={float32:Q1,int32:Z1,bool:J1,complex64:ex};function ds(n,e){if(n==="string"||e==="string"){if(n==="string"&&e==="string")return"string";throw new Error(`Can not upcast ${n} with ${e}`)}return eM[n][e]}function im(n){return ds(n,"int32")}function vC(n){return n!=null&&typeof n=="object"&&"texture"in n&&n.texture instanceof WebGLTexture}function bC(n){return typeof GPUBuffer<"u"&&n!=null&&typeof n=="object"&&"buffer"in n&&n.buffer instanceof GPUBuffer}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Un(n,e){if(n.dtype===e.dtype)return[n,e];const t=ds(n.dtype,e.dtype);return[n.cast(t),e.cast(t)]}function yC(n){const e=[];return wC(n,e,new Set),e}function wC(n,e,t){if(n==null)return;if(n instanceof Yn){e.push(n);return}if(!tM(n))return;const s=n;for(const r in s){const i=s[r];t.has(i)||(t.add(i),wC(i,e,t))}}function tM(n){return Array.isArray(n)||typeof n=="object"}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kg(n){return n.kernelName!=null}class jb{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 Rc{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new jb}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const e=this.getSortedBackends();for(let t=0;t{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Bb(e).forEach(s=>{s.disposeFunc!=null&&s.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const s=t.factory();if(s&&!(s instanceof b0)&&typeof s.then=="function"){const r=++this.pendingBackendInitId,i=s.then(o=>r(rthis.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;tthis.startScope(s),()=>this.endScope(r),()=>(r=t(),r instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),r))}scopedRun(e,t,s){e();try{const r=s();return t(),r}catch(r){throw t(),r}}nextTensorId(){return Rc.nextTensorId++}nextVariableId(){return Rc.nextVariableId++}clone(e){const t=ee.runKernel(gu,{x:e}),s={x:e},r=o=>({x:()=>{const a="float32",l={x:o},c={dtype:a};return ee.runKernel(su,l,c)}}),i=[];return this.addTapeNode(this.state.activeScope.name,s,[t],r,i,{}),t}runKernel(e,t,s){if(this.backendName==null&&this.backend,!(Ob(e,this.backendName)!=null))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:s})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,s){const r=this.backend.numDataIds();let i=0;s.forEach(l=>{i+=l.dtype==="complex64"?3:1});const o=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=r-t-i-o;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${e}'`)}runKernelFunc(e){let t,s=[];const r=this.isTapeOn(),i=this.state.numBytes,o=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let a;this.backendName==null&&this.backend;let l;const c=kg(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(kg(e)){const{kernelName:f,inputs:x,attrs:m}=e;this.backendName==null&&this.backend;const g=Ob(f,this.backendName);N(g!=null,()=>`Cannot find registered kernel '${f}' for backend '${this.backendName}'`),a=()=>{const v=this.backend.numDataIds();l=g.kernelFunc({inputs:x,attrs:m,backend:this.backend});const b=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(f,v,b);const y=b.map(w=>w.rank!=null?w:this.makeTensorFromTensorInfo(w));if(r){const w=this.getTensorsForGradient(f,x,y);s=this.saveTensorsForBackwardMode(w)}return y}}else{const{forwardFunc:f}=e,x=m=>{r&&(s=m.map(g=>this.keep(this.clone(g))))};a=()=>{const m=this.backend.numDataIds();l=this.tidy(()=>f(this.backend,x));const g=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(c,m,g),g}}const{inputs:u,attrs:h}=e,d=kg(e)?null:e.backwardsFunc;let p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=a():(p=this.profiler.profileKernel(c,u,()=>a()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs)}),r&&this.addTapeNode(c,u,t,d,s,h),this.state.profiling&&this.state.activeProfile.kernels.push({name:c,bytesAdded:this.state.numBytes-i,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-o,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(f=>u[f]!=null?u[f].shape:null),outputShapes:t.map(f=>f.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(l)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(s=>this.keep(this.clone(s)))}getTensorsForGradient(e,t,s){const r=zb(e);if(r!=null){const i=r.inputsToSave||[],o=r.outputsToSave||[];let a;r.saveAllInputs?(N(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(t).map(c=>t[c])):a=i.map(c=>t[c]);const l=s.filter((c,u)=>o[u]);return a.concat(l)}return[]}makeTensor(e,t,s,r){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");s=s||"float32",r=r||this.backend;let i=e;s==="string"&&Kc(e[0])&&(i=e.map(l=>_o(l)));const o=r.write(i,t,s),a=new Yn(t,s,o,this.nextTensorId());if(this.trackTensor(a,r),s==="string"){const l=this.state.tensorInfo.get(o),c=_R(i);this.state.numBytes+=c-l.bytes,l.bytes=c}return a}makeTensorFromDataId(e,t,s,r){s=s||"float32";const i={dataId:e,shape:t,dtype:s};return this.makeTensorFromTensorInfo(i,r)}makeTensorFromTensorInfo(e,t){const{dataId:s,shape:r,dtype:i}=e,o=new Yn(r,i,s,this.nextTensorId());return this.trackTensor(o,t),o}makeVariable(e,t=!0,s,r){s=s||this.nextVariableId().toString(),r!=null&&r!==e.dtype&&(e=e.cast(r));const i=new Df(e,t,s,this.nextTensorId());if(this.state.registeredVariables[i.name]!=null)throw new Error(`Variable with name ${i.name} was already registered`);return this.state.registeredVariables[i.name]=i,this.incRef(i,this.backend),i}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let s=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(s=e.size*Af(e.dtype)),this.state.numBytes+=s,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:s})),e instanceof Df||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--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){const s=e.size*Af(e.dtype);this.state.numBytes-=s}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),this.state.registeredVariables[e.name]!=null&&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,e.reasons==null&&(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,s=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(r=>r.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-s;for(const r of this.state.activeProfile.kernels)r.kernelTimeMs=await r.kernelTimeMs,r.extraInfo=await r.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,s,r,i,o){const a={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:s,saved:i},l=zb(e);l!=null&&(r=l.gradFunc),r!=null&&(a.gradient=c=>(c=c.map((u,h)=>{if(u==null){const d=s[h],p=Cs(d.size,d.dtype);return this.makeTensor(p,d.shape,d.dtype)}return u}),r(c.length>1?c:c[0],i,o))),this.state.activeTape.push(a)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(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=yC(e),s=new Set(t.map(i=>i.id));for(let i=0;i{!i.kept&&i.scopeId===r.id&&this.track(i)})}gradients(e,t,s,r=!1){if(N(t.length>0,()=>"gradients() received an empty list of xs."),s!=null&&s.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${s.dtype}'`);const i=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));N(i instanceof Yn,()=>"The result y returned by f() must be a tensor.");const o=KR(this.state.activeTape,t,i);if(!r&&o.length===0&&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 a={};a[i.id]=s??nM(i.shape),jR(a,o,c=>this.tidy(c),sM);const l=t.map(c=>a[c.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(c=>{for(const u of c.saved)u.dispose()}),this.state.activeTape=null),{value:i,grads:l}})}customGrad(e){return N(q1(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{N(t.every(a=>a instanceof Yn),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let s;const r={};t.forEach((a,l)=>{r[l]=a});const i=(a,l)=>(s=e(...t,l),N(s.value instanceof Yn,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),N(q1(s.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),s.value),o=(a,l)=>{const c=s.gradFunc(a,l),u=Array.isArray(c)?c:[c];N(u.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(...)."),N(u.every(d=>d instanceof Yn),()=>"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 h={};return u.forEach((d,p)=>{h[p]=()=>d}),h};return this.runKernelFunc({forwardFunc:i,backwardsFunc:o,inputs:r})}}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=qs(),s=await this.backend.time(e);return s.wallMs=qs()-t,s}track(e){return this.state.activeScope!=null&&(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 jb;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}}Rc.nextTensorId=0;Rc.nextVariableId=0;function nM(n){const e=o2(re(n),"float32");return ee.makeTensor(e,n,"float32")}function SC(){const n=ZS();if(n._tfengine==null){const e=new IR(n);n._tfengine=new Rc(e)}return RR(n._tfengine.ENV),JR(()=>n._tfengine),n._tfengine}const ee=SC();function sM(n,e){const t={a:n,b:e};return ee.runKernel(El,t)}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rM(){return typeof navigator<"u"&&navigator!=null}function CC(n){if(n||rM()){if(n||(n=navigator),n.product==="ReactNative")return!0;const e=n.userAgent||n.vendor||(typeof window<"u"?window.opera:"");if(!e){const t=n;return t.userAgentData&&t.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))}return!1}function _C(){return typeof window<"u"&&window.document!=null||typeof WorkerGlobalScope<"u"}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rr=oe();rr.registerFlag("DEBUG",()=>!1,n=>{n&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")});rr.registerFlag("IS_BROWSER",()=>_C());rr.registerFlag("IS_NODE",()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u");rr.registerFlag("IS_CHROME",()=>typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));rr.registerFlag("IS_SAFARI",()=>typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor));rr.registerFlag("PROD",()=>!1);rr.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>rr.getBool("DEBUG"));rr.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);rr.registerFlag("IS_TEST",()=>!1);rr.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>rr.getBool("DEBUG"));rr.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);rr.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1);rr.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function om(n,e){let t=n;if(ei(n))return e==="string"?[]:[n.length];if(vC(n)){const r=n.channels||"RGBA";return[n.height,n.width*r.length]}else if(bC(n))return[n.buffer.size/(e==null?4:Af(e))];if(!Array.isArray(n))return[];const s=[];for(;Array.isArray(t)||ei(t)&&e!=="string";)s.push(t.length),t=t[0];return Array.isArray(n)&&oe().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&TC(n,s,[]),s}function TC(n,e,t){if(t=t||[],!Array.isArray(n)&&!ei(n)){N(e.length===0,()=>`Element arr[${t.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`);return}N(e.length>0,()=>`Element arr[${t.join("][")}] should be a primitive, but is an array of ${n.length} elements`),N(n.length===e[0],()=>`Element arr[${t.join("][")}] should have ${e[0]} elements, but has ${n.length} elements`);const s=e.slice(1);for(let r=0;r=0&&(r=s),Yb(s,r,e,t),n==null||!ei(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string"){const l=n==null?"null":n.constructor.name;throw new Error(`Argument '${e}' passed to '${t}' must be a Tensor or TensorLike, but got '${l}'`)}const i=om(n,r);!ei(n)&&!Array.isArray(n)&&(n=[n]);const a=r!=="string"?Rl(n,r):ko(n,[],!0);return ee.makeTensor(a,i,r)}function IC(n,e,t,s="numeric"){if(!Array.isArray(n))throw new Error(`Argument ${e} passed to ${t} must be a \`Tensor[]\` or \`TensorLike[]\``);return n.map((i,o)=>G(i,`${e}[${o}]`,t,s))}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iM="__op";function ie(n){const e=Object.keys(n);if(e.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${e.length} keys.`);let t=e[0];const s=n[t];t.endsWith("_")&&(t=t.substring(0,t.length-1)),t=t+iM;const r=(...i)=>{ee.startScope(t);try{const o=s(...i);return a2(o)&&console.error("Cannot return a Promise inside of tidy."),ee.endScope(o),o}catch(o){throw ee.endScope(null),o}};return Object.defineProperty(r,"name",{value:t,configurable:!0}),r}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oM(n,e){const t=G(n,"real","complex"),s=G(e,"imag","complex");y0(t.shape,s.shape,`real and imag shapes, ${t.shape} and ${s.shape}, must match in call to tf.complex().`);const r={real:t,imag:s};return ee.runKernel(E0,r)}const Mc=ie({complex_:oM});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function am(n,e,t,s){if(s==null)s=Il(n);else if(s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(bC(n)||vC(n)){if(s!=="float32"&&s!=="int32")throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${s}.`);return ee.backend.createTensorFromGPUData(n,e||t,s)}if(!ei(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string")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(e!=null){No(e);const r=re(e),i=re(t);N(r===i,()=>`Based on the provided shape, [${e}], the tensor should have ${r} values but has ${i}`);for(let o=0;o`Error creating a new Tensor. Inferred shape (${t}) does not match the provided shape (${e}). `)}}return!ei(n)&&!Array.isArray(n)&&(n=[n]),e=e||t,n=s!=="string"?Rl(n,s):ko(n,[],!0),ee.makeTensor(n,e,s)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function EC(n,e,t){const s=om(n,t);return am(n,e,s,t)}class wa{static join(e){return new wa(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,e==null||(e instanceof Array||(e=[e]),e=e.map(s=>ei(s)?s.buffer:s),e.length===0))return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let s=0;s=this.byteLength)return-1;if(this.bufferUniformSize!=null)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(r){return e=r.end?1:0}if(t(this.shards[this.previousShardIndex])===0)return this.previousShardIndex;const s=aM(this.shards,t);return s===-1?-1:(this.previousShardIndex=s,this.previousShardIndex)}}function aM(n,e){let t=0,s=n.length;for(;t<=s;){const r=Math.floor((s-t)/2)+t,i=e(n[r]);if(i===0)return r;i<0?s=r:t=r+1}return-1}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Tr(){return ee}function tx(){return ee.memory()}function le(n,e){return ee.tidy(n,e)}function Nt(n){yC(n).forEach(t=>t.dispose())}function er(n){return ee.keep(n)}function Zb(n){return ee.setBackend(n)}function Jb(){return ee.ready()}function A2(n,e,t=1){return ee.registerBackend(n,e,t)}function lM(){return ee.backend}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qb=4;async function ey(n,e){const t=[],s=[],r=Array.isArray(n)?n.map(o=>o.name):Object.keys(n);for(let o=0;o{const d=await l.bytes(),p=d.reduce((m,g)=>m+g.length,0)+Qb*d.length,f=new Uint8Array(p);let x=0;for(let m=0;m{if(e+=i.byteLength,t.push(i.byteLength===i.buffer.byteLength?i:new i.constructor(i)),!(i instanceof Float32Array||i instanceof Int32Array||i instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${i.constructor.name}`)});const s=new Uint8Array(e);let r=0;return t.forEach(i=>{s.set(new Uint8Array(i.buffer),r),r+=i.byteLength}),s.buffer}const R2=typeof Buffer<"u"&&(typeof Blob>"u"||typeof atob>"u"||typeof btoa>"u");function ty(n){return R2?Buffer.byteLength(n,"utf8"):new Blob([n]).size}function uM(n){if(R2)return Buffer.from(n).toString("base64");const e=new Uint8Array(n);let t="";for(let s=0,r=e.length;s{const a=o(e,s);a!==null&&r.push(a)}),r}}const mM=n=>ls.getSaveHandlers(n);/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nx="tensorflowjs",sx=1,el="models_store",Ko="model_info_store";function AC(){if(!oe().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const n=typeof window>"u"?self:window,e=n.indexedDB||n.mozIndexedDB||n.webkitIndexedDB||n.msIndexedDB||n.shimIndexedDB;if(e==null)throw new Error("The current browser does not appear to support IndexedDB.");return e}function rx(n){const e=n.result;e.createObjectStore(el,{keyPath:"modelPath"}),e.createObjectStore(Ko,{keyPath:"modelPath"})}class dl{constructor(e){if(this.indexedDB=AC(),e==null||!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((s,r)=>{const i=this.indexedDB.open(nx,sx);i.onupgradeneeded=()=>rx(i),i.onsuccess=()=>{const o=i.result;if(t==null){const a=o.transaction(el,"readonly"),c=a.objectStore(el).get(this.modelPath);c.onsuccess=()=>{if(c.result==null)return o.close(),r(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));s(c.result.modelArtifacts)},c.onerror=u=>(o.close(),r(c.error)),a.oncomplete=()=>o.close()}else{t.weightData=wa.join(t.weightData);const a=lm(t),l=o.transaction(Ko,"readwrite");let c=l.objectStore(Ko),u;try{u=c.put({modelPath:this.modelPath,modelArtifactsInfo:a})}catch(d){return r(d)}let h;u.onsuccess=()=>{h=o.transaction(el,"readwrite");const d=h.objectStore(el);let p;try{p=d.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:a})}catch(f){return r(f)}p.onsuccess=()=>s({modelArtifactsInfo:a}),p.onerror=f=>{c=l.objectStore(Ko);const x=c.delete(this.modelPath);x.onsuccess=()=>(o.close(),r(p.error)),x.onerror=m=>(o.close(),r(p.error))}},u.onerror=d=>(o.close(),r(u.error)),l.oncomplete=()=>{h==null?o.close():h.oncomplete=()=>o.close()}}},i.onerror=o=>r(i.error)})}}dl.URL_SCHEME="indexeddb://";const RC=n=>oe().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(dl.URL_SCHEME)?gM(n.slice(dl.URL_SCHEME.length)):null;ls.registerSaveRouter(RC);ls.registerLoadRouter(RC);function gM(n){return new dl(n)}function xM(n){return n.startsWith(dl.URL_SCHEME)?n.slice(dl.URL_SCHEME.length):n}class vM{constructor(){this.indexedDB=AC()}async listModels(){return new Promise((e,t)=>{const s=this.indexedDB.open(nx,sx);s.onupgradeneeded=()=>rx(s),s.onsuccess=()=>{const r=s.result,i=r.transaction(Ko,"readonly"),a=i.objectStore(Ko).getAll();a.onsuccess=()=>{const l={};for(const c of a.result)l[c.modelPath]=c.modelArtifactsInfo;e(l)},a.onerror=l=>(r.close(),t(a.error)),i.oncomplete=()=>r.close()},s.onerror=r=>t(s.error)})}async removeModel(e){return e=xM(e),new Promise((t,s)=>{const r=this.indexedDB.open(nx,sx);r.onupgradeneeded=()=>rx(r),r.onsuccess=()=>{const i=r.result,o=i.transaction(Ko,"readwrite"),a=o.objectStore(Ko),l=a.get(e);let c;l.onsuccess=()=>{if(l.result==null)return i.close(),s(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const u=a.delete(e),h=()=>{c=i.transaction(el,"readwrite");const p=c.objectStore(el).delete(e);p.onsuccess=()=>t(l.result.modelArtifactsInfo),p.onerror=f=>s(l.error)};u.onsuccess=h,u.onerror=d=>(h(),i.close(),s(l.error))}},l.onerror=u=>(i.close(),s(l.error)),o.oncomplete=()=>{c==null?i.close():c.oncomplete=()=>i.close()}},r.onerror=i=>s(r.error)})}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bo="/",gc="tensorflowjs_models",MC="info",bM="model_topology",yM="weight_specs",wM="weight_data",SM="model_metadata";function NC(n){return{info:[gc,n,MC].join(bo),topology:[gc,n,bM].join(bo),weightSpecs:[gc,n,yM].join(bo),weightData:[gc,n,wM].join(bo),modelMetadata:[gc,n,SM].join(bo)}}function $C(n){for(const e of Object.values(n))window.localStorage.removeItem(e)}function CM(n){const e=n.split(bo);if(e.length<3)throw new Error(`Invalid key format: ${n}`);return e.slice(1,e.length-1).join(bo)}function _M(n){return n.startsWith(pl.URL_SCHEME)?n.slice(pl.URL_SCHEME.length):n}class pl{constructor(e){if(!oe().getBool("IS_BROWSER")||typeof window>"u"||typeof window.localStorage>"u")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,e==null||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=NC(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),s=JSON.stringify(e.weightSpecs),r=lm(e),i=wa.join(e.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,s),this.LS.setItem(this.keys.weightData,uM(i));const o={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:void 0,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:void 0,modelInitializer:e.modelInitializer!=null?e.modelInitializer:void 0,initializerSignature:e.initializerSignature!=null?e.initializerSignature:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(o)),{modelArtifactsInfo:r}}catch{throw $C(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${r.modelTopologyBytes}, weightSpecsBytes=${r.weightSpecsBytes}, weightDataBytes=${r.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},s=JSON.parse(this.LS.getItem(this.keys.topology));if(s==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=s;const r=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(r==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=r;const i=this.LS.getItem(this.keys.modelMetadata);if(i!=null){const a=JSON.parse(i);t.format=a.format,t.generatedBy=a.generatedBy,t.convertedBy=a.convertedBy,a.signature!=null&&(t.signature=a.signature),a.userDefinedMetadata!=null&&(t.userDefinedMetadata=a.userDefinedMetadata),a.modelInitializer!=null&&(t.modelInitializer=a.modelInitializer),a.initializerSignature!=null&&(t.initializerSignature=a.initializerSignature),a.trainingConfig!=null&&(t.trainingConfig=a.trainingConfig)}const o=this.LS.getItem(this.keys.weightData);if(o==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=hM(o),t}}pl.URL_SCHEME="localstorage://";const DC=n=>oe().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(pl.URL_SCHEME)?TM(n.slice(pl.URL_SCHEME.length)):null;ls.registerSaveRouter(DC);ls.registerLoadRouter(DC);function TM(n){return new pl(n)}class IM{constructor(){N(oe().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),N(typeof window>"u"||typeof window.localStorage<"u",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const e={},t=gc+bo,s=bo+MC;for(let r=0;r"scheme must not be undefined or null."),e.endsWith(sy)&&(e=e.slice(0,e.indexOf(sy))),N(e.length>0,()=>"scheme must not be an empty string.");const s=Di.getInstance();N(s.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),s.managers[e]=t}static getManager(e){const t=Di.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Di.getInstance().managers)}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class EM{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){if(typeof window>"u"||!oe().getBool("USE_SETTIMEOUTCUSTOM")){setTimeout(e,t);return}this.functionRefs.push(e),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",s=>{if(s.source===window&&s.data.name===this.messageName){s.stopPropagation();const r=this.functionRefs[s.data.index];r(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))}isTypedArray(e){return lC(e)}}if(oe().get("IS_BROWSER")){oe().setPlatform("browser",new EM);try{Di.registerManager(pl.URL_SCHEME,new IM)}catch{}try{Di.registerManager(dl.URL_SCHEME,new vM)}catch{}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kM={importFetch:()=>require("node-fetch")};let Ag;class AM{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return oe().global.fetch!=null?oe().global.fetch(e,t):(Ag==null&&(Ag=kM.importFetch()),Ag(e,t))}now(){const e=process.hrtime();return e[0]*1e3+e[1]/1e6}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return e.length===0?"":new this.util.TextDecoder(t).decode(e)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}}oe().get("IS_NODE")&&!oe().get("IS_BROWSER")&&oe().setPlatform("node",new AM);/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Tt(n,e="float32",t){return e=e||"float32",No(n),new Ss(n,e,t)}/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function RM(n,e){const t=G(n,"x","cast");if(!CR(e))throw new Error(`Failed to cast to unknown dtype ${e}`);if(e==="string"&&t.dtype!=="string"||e!=="string"&&t.dtype==="string")throw new Error("Only strings can be casted to strings");const s={x:t},r={dtype:e};return ee.runKernel(su,s,r)}const qe=ie({cast_:RM});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function MM(n){const t={x:G(n,"x","clone","string_or_numeric")};return ee.runKernel(gu,t)}const il=ie({clone_:MM});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function NM(n,e=!1){console.log(n.toString(e))}/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */SC();const $M={buffer:Tt,cast:qe,clone:il,print:NM};QR($M);/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function DM(n,e){let t=G(n,"a","add"),s=G(e,"b","add");[t,s]=Un(t,s);const r={a:t,b:s};return ee.runKernel(El,r)}const ke=ie({add_:DM});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function PM(n,e){let t=G(n,"a","floorDiv"),s=G(e,"b","floorDiv");[t,s]=Un(t,s);const r={a:t,b:s};return ee.runKernel(fu,r)}const PC=ie({floorDiv_:PM});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function LM(n,e){let t=G(n,"a","div"),s=G(e,"b","div");if([t,s]=Un(t,s),t.dtype==="int32"&&s.dtype==="int32")return PC(t,s);const r={a:t,b:s},i={};return ee.runKernel(lu,r,i)}const ut=ie({div_:LM});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function FM(n,e){let t=G(n,"a","mul"),s=G(e,"b","mul");[t,s]=Un(t,s);const r={a:t,b:s};return ee.runKernel(Tu,r)}const Z=ie({mul_:FM});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function OM(n){const e=G(n,"x","abs");if(e.dtype==="complex64"){const t={x:e};return ee.runKernel(ld,t)}else{const t={x:e};return ee.runKernel(td,t)}}const Ls=ie({abs_:OM});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zM(n){const t={x:G(n,"x","acos")};return ee.runKernel(Yc,t)}const BM=ie({acos_:zM});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function UM(n){const t={x:G(n,"x","acosh")};return ee.runKernel(Zc,t)}const VM=ie({acosh_:UM});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function WM(n,e=null,t=!1){const r={x:G(n,"x","all","bool")},i={axis:e,keepDims:t};return ee.runKernel(S0,r,i)}const LC=ie({all_:WM});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function GM(n,e=null,t=!1){const r={x:G(n,"x","any","bool")},i={axis:e,keepDims:t};return ee.runKernel(C0,r,i)}const ix=ie({any_:GM});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function HM(n,e=0){const s={x:G(n,"x","argMax")},r={axis:e};return ee.runKernel(nd,s,r)}const Fh=ie({argMax_:HM});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qM(n,e=0){const s={x:G(n,"x","argMin")},r={axis:e};return ee.runKernel(sd,s,r)}const XM=ie({argMin_:qM});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function KM(n){const t={x:G(n,"x","asin")};return ee.runKernel(Jc,t)}const jM=ie({asin_:KM});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function YM(n){const t={x:G(n,"x","asinh")};return ee.runKernel(Qc,t)}const ZM=ie({asinh_:YM});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function JM(n){const t={x:G(n,"x","atan")};return ee.runKernel(eu,t)}const QM=ie({atan_:JM});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function eN(n,e){let t=G(n,"a","atan2"),s=G(e,"b","atan2");[t,s]=Un(t,s);const r={a:t,b:s};return ee.runKernel(nu,r)}const tN=ie({atan2_:eN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nN(n){const t={x:G(n,"x","atanh")};return ee.runKernel(tu,t)}const sN=ie({atanh_:nN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Sa(n,e,t,s,r="NHWC",i){const o=n[3],a=[...e,o],l=wr(r);return Cn(n,a,t,i,s,null,null,l)}function Rs(n,e,t,s,r,i,o="channelsLast"){const[a,l]=Oh(e);let c;if(o==="channelsLast")c=[a,l,n[3],n[3]];else if(o==="channelsFirst")c=[a,l,n[1],n[1]];else throw new Error(`Unknown dataFormat ${o}`);return Cn(n,c,t,s,r,i,!1,o)}function $r(n,e,t,s,r,i,o="NDHWC"){const[a,l,c]=ox(e);let u,h;if(o==="NDHWC")h="channelsLast",u=[a,l,c,n[4],n[4]];else if(o==="NCDHW")h="channelsFirst",u=[a,l,c,n[1],n[1]];else throw new Error(`Unknown dataFormat ${o}`);return Ri(n,u,t,s,r,!1,h,i)}function Cn(n,e,t,s,r,i,o=!1,a="channelsLast"){let[l,c,u,h]=[-1,-1,-1,-1];if(a==="channelsLast")[l,c,u,h]=n;else if(a==="channelsFirst")[l,h,c,u]=n;else throw new Error(`Unknown dataFormat ${a}`);const[d,p,,f]=e,[x,m]=Oh(t),[g,v]=Oh(s),b=wc(d,g),y=wc(p,v),{padInfo:w,outHeight:C,outWidth:T}=oN(r,c,u,x,m,b,y,i,a),E=o?f*h:f;let R;return a==="channelsFirst"?R=[l,E,C,T]:a==="channelsLast"&&(R=[l,C,T,E]),{batchSize:l,dataFormat:a,inHeight:c,inWidth:u,inChannels:h,outHeight:C,outWidth:T,outChannels:E,padInfo:w,strideHeight:x,strideWidth:m,filterHeight:d,filterWidth:p,effectiveFilterHeight:b,effectiveFilterWidth:y,dilationHeight:g,dilationWidth:v,inShape:n,outShape:R,filterShape:e}}function Ri(n,e,t,s,r,i=!1,o="channelsLast",a){let[l,c,u,h,d]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[l,c,u,h,d]=n;else if(o==="channelsFirst")[l,d,c,u,h]=n;else throw new Error(`Unknown dataFormat ${o}`);const[p,f,x,,m]=e,[g,v,b]=ox(t),[y,w,C]=ox(s),T=wc(p,y),E=wc(f,w),R=wc(x,C),{padInfo:_,outDepth:k,outHeight:F,outWidth:B}=aN(r,c,u,h,g,v,b,T,E,R,a),M=i?m*d:m;let P;return o==="channelsFirst"?P=[l,M,k,F,B]:o==="channelsLast"&&(P=[l,k,F,B,M]),{batchSize:l,dataFormat:o,inDepth:c,inHeight:u,inWidth:h,inChannels:d,outDepth:k,outHeight:F,outWidth:B,outChannels:M,padInfo:_,strideDepth:g,strideHeight:v,strideWidth:b,filterDepth:p,filterHeight:f,filterWidth:x,effectiveFilterDepth:T,effectiveFilterHeight:E,effectiveFilterWidth:R,dilationDepth:y,dilationHeight:w,dilationWidth:C,inShape:n,outShape:P,filterShape:e}}function rN(n,e,t,s,r){s==null&&(s=M2(n,e,t));const i=n[0],o=n[1],a=zh((i-e+2*s)/t+1,r),l=zh((o-e+2*s)/t+1,r);return[a,l]}function iN(n,e,t,s,r,i){r==null&&(r=M2(n,e[0],s[0]));const o=[0,0,0,t];for(let a=0;a<3;a++)n[a]+2*r>=e[a]&&(o[a]=zh((n[a]-e[a]+2*r)/s[a]+1,i));return o}function M2(n,e,t,s=1){const r=wc(e,s);return Math.floor((n[0]*(t-1)-t+r)/2)}function Oh(n){return typeof n=="number"?[n,n,n]:n.length===2?[n[0],n[1],1]:n}function ox(n){return typeof n=="number"?[n,n,n]:n}function wc(n,e){return e<=1?n:n+(n-1)*(e-1)}function oN(n,e,t,s,r,i,o,a,l){let c,u,h;if(typeof n=="number"){c={top:n,bottom:n,left:n,right:n,type:n===0?"VALID":"NUMBER"};const p=rN([e,t],i,s,n,a);u=p[0],h=p[1]}else if(n==="same"){u=Math.ceil(e/s),h=Math.ceil(t/r);const d=Math.max(0,(u-1)*s+i-e),p=Math.max(0,(h-1)*r+o-t),f=Math.floor(d/2),x=d-f,m=Math.floor(p/2),g=p-m;c={top:f,bottom:x,left:m,right:g,type:"SAME"}}else if(n==="valid")c={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((e-i+1)/s),h=Math.ceil((t-o+1)/r);else if(typeof n=="object"){const d=l==="channelsLast"?n[1][0]:n[2][0],p=l==="channelsLast"?n[1][1]:n[2][1],f=l==="channelsLast"?n[2][0]:n[3][0],x=l==="channelsLast"?n[2][1]:n[3][1];c={top:d,bottom:p,left:f,right:x,type:d===0&&p===0&&f===0&&x===0?"VALID":"EXPLICIT"},u=zh((e-i+d+p)/s+1,a),h=zh((t-o+f+x)/r+1,a)}else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:c,outHeight:u,outWidth:h}}function aN(n,e,t,s,r,i,o,a,l,c,u){let h,d,p,f;if(n==="valid"&&(n=0),typeof n=="number"){h={top:n,bottom:n,left:n,right:n,front:n,back:n,type:n===0?"VALID":"NUMBER"};const m=iN([e,t,s,1],[a,l,c],1,[r,i,o],n,u);d=m[0],p=m[1],f=m[2]}else if(n==="same"){d=Math.ceil(e/r),p=Math.ceil(t/i),f=Math.ceil(s/o);const x=(d-1)*r+a-e,m=(p-1)*i+l-t,g=(f-1)*o+c-s,v=Math.floor(x/2),b=x-v,y=Math.floor(m/2),w=m-y,C=Math.floor(g/2),T=g-C;h={top:y,bottom:w,left:C,right:T,front:v,back:b,type:"SAME"}}else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:h,outDepth:d,outHeight:p,outWidth:f}}function zh(n,e){if(!e)return Math.trunc(n);switch(e){case"round":return Math.round(n);case"ceil":return Math.ceil(n);case"floor":return Math.floor(n);default:throw new Error(`Unknown roundingMode ${e}`)}}function fl(n){const[e,t,s]=Oh(n);return e===1&&t===1&&s===1}function gs(n,e){return fl(n)||fl(e)}function ml(n){return Oh(n).every(e=>e>0)}function wr(n){if(n==="NHWC")return"channelsLast";if(n==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${n}`)}function or(n,e,t){if(t!=null){if(typeof e=="string")throw Error(`Error in ${n}: pad must be an integer when using dimRoundingMode ${t} but got pad ${e}.`);if(typeof e=="number")N(kc(e),()=>`Error in ${n}: pad must be an integer when using dimRoundingMode ${t} but got pad ${e}.`);else if(typeof e=="object")e.forEach(s=>{s.forEach(r=>{N(kc(r),()=>`Error in ${n}: pad must be an integer when using dimRoundingMode ${t} but got pad ${r}.`)})});else throw Error(`Error in ${n}: Unknown padding parameter: ${e}`)}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lN(n,e){const s={x:G(n,"x","reshape","string_or_numeric")},r={shape:e};return ee.runKernel(Vd,s,r)}const se=ie({reshape_:lN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cN(n,e,t,s,r){const i=G(n,"x","avgPool","float32"),o=1;N(gs(t,o),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${o}'`);let a=i,l=!1;i.rank===3&&(l=!0,a=se(i,[1,i.shape[0],i.shape[1],i.shape[2]])),N(a.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${a.rank}.`),or("avgPool",s,r);const c={x:a},u={filterSize:e,strides:t,pad:s,dimRoundingMode:r};let h=ee.runKernel(rd,c,u);return h=qe(h,i.dtype),l?se(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const N2=ie({avgPool_:cN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function uN(n,e,t,s,r,i="NDHWC"){const o=G(n,"x","avgPool3d","float32");let a=o,l=!1;o.rank===4&&(l=!0,a=se(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),N(a.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${a.rank}.`),N(i==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${i}`),N(typeof t=="number"&&t>0||Array.isArray(t)&&t[0]>0&&t[1]>0&&t[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got '${t}'`),or("avgPool3d",s,r);const c={x:a},u={filterSize:e,strides:t,pad:s,dimRoundingMode:r,dataFormat:i};let h=ee.runKernel(id,c,u);return h=qe(h,a.dtype),l?se(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}const hN=ie({avgPool3d_:uN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function dN(n,e=0){N(n.length>=1,()=>"Pass at least one tensor to concat");const t=IC(n,"tensors","concat","string_or_numeric");if(t[0].dtype==="complex64"&&t.forEach(i=>{if(i.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor + with dtype ${i.dtype}. `)}),t.length===1)return il(t[0]);const s=t,r={axis:e};return ee.runKernel(cd,s,r)}const tr=ie({concat_:dN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pN(n,e,t=!1,s=!1){let r=G(n,"a","matMul"),i=G(e,"b","matMul");[r,i]=Un(r,i);const o={a:r,b:i},a={transposeA:t,transposeB:s};return ee.runKernel(od,o,a)}const Jt=ie({matMul_:pN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fN(n){const t={x:G(n,"x","sigmoid","float32")};return ee.runKernel(Lu,t)}const Hu=ie({sigmoid_:fN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mN(n,e,t){const s=G(n,"x","slice","string_or_numeric");if(s.rank===0)throw new Error("Slicing scalar is not possible");const r={x:s},i={begin:e,size:t};return ee.runKernel(Xd,r,i)}const fn=ie({slice_:mN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gN(n){const t={x:G(n,"x","tanh","float32")};return ee.runKernel(Vu,t)}const Nc=ie({tanh_:gN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xN(n,e,t){const s=G(n,"x","batchToSpaceND"),r=e.reduce((a,l)=>a*l);N(s.rank>=1+e.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${e.length}`),N(t.length===e.length,()=>`crops.length is ${t.length} but should be equal to blockShape.length ${e.length}`),N(s.shape[0]%r===0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${e.join(" * ")} === ${r}`);const i={x:s},o={blockShape:e,crops:t};return ee.runKernel(ad,i,o)}const $2=ie({batchToSpaceND_:xN});function vN(n){let e;return n.rank===0||n.rank===1?e=se(n,[1,1,1,n.size]):n.rank===2?e=se(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?e=se(n,[1,n.shape[0],n.shape[1],n.shape[2]]):e=n,e}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bN(n,e,t,s,r,i){i==null&&(i=.001);const o=G(n,"x","batchNorm"),a=G(e,"mean","batchNorm"),l=G(t,"variance","batchNorm");let c;r!=null&&(c=G(r,"scale","batchNorm"));let u;s!=null&&(u=G(s,"offset","batchNorm")),N(a.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),N(u==null||a.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),N(c==null||a.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const d={x:vN(o),scale:c,offset:u,mean:a,variance:l},p={varianceEpsilon:i},f=ee.runKernel(vd,d,p);return se(f,o.shape)}const cm=ie({batchNorm_:bN});function yN(n,e,t,s,r,i){const o=G(n,"x","batchNorm"),a=G(e,"mean","batchNorm"),l=G(t,"variance","batchNorm");let c;r!=null&&(c=G(r,"scale","batchNorm"));let u;return s!=null&&(u=G(s,"offset","batchNorm")),N(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),N(a.rank===2||a.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${a.rank}.`),N(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&N(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),u!=null&&N(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),cm(o,a,l,u,c,i)}const wN=ie({batchNorm2d_:yN});function SN(n,e,t,s,r,i){const o=G(n,"x","batchNorm"),a=G(e,"mean","batchNorm"),l=G(t,"variance","batchNorm");let c;r!=null&&(c=G(r,"scale","batchNorm"));let u;return s!=null&&(u=G(s,"offset","batchNorm")),N(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),N(a.rank===3||a.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${a.rank}.`),N(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&N(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),u!=null&&N(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),cm(o,a,l,u,c,i)}const CN=ie({batchNorm3d_:SN});function _N(n,e,t,s,r,i){const o=G(n,"x","batchNorm"),a=G(e,"mean","batchNorm"),l=G(t,"variance","batchNorm");let c;r!=null&&(c=G(r,"scale","batchNorm"));let u;return s!=null&&(u=G(s,"offset","batchNorm")),N(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),N(a.rank===4||a.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${a.rank}.`),N(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),c!=null&&N(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),u!=null&&N(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),cm(o,a,l,u,c,i)}const TN=ie({batchNorm4d_:_N});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function IN(n,e,t){const s=G(n,"x","bincount"),r=G(e,"weights","bincount");N(s.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`),N(t>=0,()=>`size must be non-negative, but got ${t}.`),N(r.size===s.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`);const i={x:s,weights:r},o={size:t};return ee.runKernel(I0,i,o)}const EN=ie({bincount_:IN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kN(n,e){let t=G(n,"broadcastTo","x");const s=t.shape;if(No(e),e.lengtht.rank){const c=t.shape.slice();for(;c.length=0;c--)if(r[c]===e[c])i[c]=1;else if(t.shape[c]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${e}].`);if(i.map((c,u)=>c>1?u:-1).filter(c=>c>=0).length===0)return il(t);const a={x:t},l={reps:i};return ee.runKernel(Wu,a,l)}const Mh=ie({broadcastTo_:kN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function AN(n){const t={x:G(n,"x","ceil","float32")};return ee.runKernel(ru,t)}const RN=ie({ceil_:AN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function um(n,e,t){No(n),t=t||Il(e);const s={shape:n,value:e,dtype:t};return ee.runKernel(B0,{},s)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function MN(n,e,t){const s=G(n,"x","clipByValue");if(N(e<=t,()=>`Error in clip: min (${e}) must be less than or equal to max (${t}).`),e===t)return um(s.shape,e,s.dtype);const r={x:s},i={clipValueMin:e,clipValueMax:t};return ee.runKernel(iu,r,i)}const Mr=ie({clipByValue_:MN});function NN(n){return tr(n,0)}const $N=ie({concat1d_:NN});function DN(n,e){return tr(n,e)}const PN=ie({concat2d_:DN});function LN(n,e){return tr(n,e)}const FN=ie({concat3d_:LN});function ON(n,e){return tr(n,e)}const zN=ie({concat4d_:ON});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function BN(n,e,t,s,r="NHWC",i=[1,1],o){const a=G(n,"x","conv2d","float32"),l=G(e,"filter","conv2d","float32");let c=a,u=!1;a.rank===3&&(u=!0,c=se(a,[1,a.shape[0],a.shape[1],a.shape[2]])),N(c.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),N(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),or("conv2d",s,o);const h=r==="NHWC"?c.shape[3]:c.shape[1];N(h===l.shape[2],()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`),N(gs(t,i),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${i}'`),N(ml(i),()=>"Error in conv2D: Dilated rates should be larger than 0."),N(ml(t),()=>"Error in conv2D: Strides should be larger than 0.");const d={x:c,filter:l},p={strides:t,pad:s,dataFormat:r,dilations:i,dimRoundingMode:o},f=ee.runKernel(ud,d,p);return u?se(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const gl=ie({conv2d_:BN});function UN(n,e,t,s,r="NWC",i=1,o){const a=G(n,"x","conv1d"),l=G(e,"filter","conv1d");let c=a,u=!1;a.rank===2&&(u=!0,c=se(a,[1,a.shape[0],a.shape[1]])),N(c.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),N(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),or("conv1d",s,o),N(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),N(gs(t,i),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${t} and dilation '${i}'`),N(ml(i),()=>"Error in conv1D: Dilated rates should be larger than 0."),N(ml(t),()=>"Error in conv1D: Stride should be larger than 0."),N(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);const h=se(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=se(c,[c.shape[0],1,c.shape[1],c.shape[2]]),m=gl(d,h,[1,t],s,"NHWC",[1,i],o);return u?se(m,[m.shape[2],m.shape[3]]):se(m,[m.shape[0],m.shape[2],m.shape[3]])}const FC=ie({conv1d_:UN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function VN(n,e,t,s,r,i="NHWC",o){N(n.length===e.rank,()=>`Length of inShape (${n.length}) and rank of dy (${e.rank}) must match`);let a=n,l=e,c=!1;e.rank===3&&(c=!0,l=se(e,[1,e.shape[0],e.shape[1],e.shape[2]]),a=[1,n[0],n[1],n[2]]),N(a.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${a.length}.`),N(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),N(t.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${t.rank}`);const u=i==="NHWC"?a[3]:a[1],h=i==="NHWC"?l.shape[3]:l.shape[1];N(u===t.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${t.shape[2]}.`),N(h===t.shape[3],()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${t.shape[3]}.`),or("conv2dDerInput",r,o);const d={dy:l,filter:t},p={strides:s,pad:r,dataFormat:i,dimRoundingMode:o,inputShape:a},f=ee.runKernel(hd,d,p);return c?se(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const D2=ie({conv2DBackpropInput_:VN});function WN(n,e,t,s,r,i){const o=G(n,"x","conv2dTranspose"),a=G(e,"filter","conv2dTranspose");return D2(t,o,a,s,r,"NHWC",i)}const OC=ie({conv2dTranspose_:WN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function GN(n,e,t,s,r="NDHWC",i=[1,1,1]){const o=G(n,"x","conv3d"),a=G(e,"filter","conv3d");let l=o,c=!1;o.rank===4&&(c=!0,l=se(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),N(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),N(a.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${a.rank}.`),N(l.shape[4]===a.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${a.shape[3]}.`),N(gs(t,i),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${t} and dilations '${i}'`),N(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`),N(ml(i),()=>"Error in conv3D: Dilated rates should be larger than 0."),N(ml(t),()=>"Error in conv3D: Strides should be larger than 0.");const u={x:l,filter:a},h={strides:t,pad:s,dataFormat:r,dilations:i},d=ee.runKernel(dd,u,h);return c?se(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const HN=ie({conv3d_:GN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qN(n,e,t,s,r){N(n.length===e.rank,()=>`Length of inShape (${n.length}) and rank of dy (${e.rank}) must match`);let i=n,o=e,a=!1;e.rank===4&&(a=!0,o=se(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]),i=[1,n[0],n[1],n[2],n[3]]);const l=i[4],c=o.shape[4];N(i.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${i.length}.`),N(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),N(t.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${t.rank}`),N(l===t.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${t.shape[3]}.`),N(c===t.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${t.shape[4]}.`);const u={dy:o,filter:t},h={pad:r,strides:s,inputShape:i},d=ee.runKernel(R0,u,h);return a?se(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const zC=ie({conv3DBackpropInput_:qN});function XN(n,e,t,s,r){const i=G(n,"x","conv3dTranspose"),o=G(e,"filter","conv3dTranspose");return zC(t,i,o,s,r)}const KN=ie({conv3dTranspose_:XN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jN(n){const t={x:G(n,"x","cos","float32")};return ee.runKernel(ou,t)}const P2=ie({cos_:jN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function YN(n){const t={x:G(n,"x","cosh","float32")};return ee.runKernel(au,t)}const BC=ie({cosh_:YN});/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ZN(n,e=0,t=!1,s=!1){const i={x:G(n,"x","cumprod")},o={axis:e,exclusive:t,reverse:s};return ee.runKernel(M0,i,o)}const ax=ie({cumprod_:ZN});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function JN(n,e=0,t=!1,s=!1){const i={x:G(n,"x","cumsum")},o={axis:e,exclusive:t,reverse:s};return ee.runKernel(pd,i,o)}const UC=ie({cumsum_:JN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function QN(n,e,t,s=!1){const r=G(n,"x","denseBincount"),i=G(e,"weights","denseBincount");N(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),N(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),N(t>=0,()=>`size must be non-negative, but got ${t}.`),N(i.size===r.size||i.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${i.shape}.`);const o={x:r,weights:i},a={size:t,binaryOutput:s};return ee.runKernel($0,o,a)}const ry=ie({denseBincount_:QN});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function e5(n,e,t="NHWC"){const s=G(n,"x","depthToSpace","float32"),r=t==="NHWC"?s.shape[1]:s.shape[2],i=t==="NHWC"?s.shape[2]:s.shape[3],o=t==="NHWC"?s.shape[3]:s.shape[1];N(e>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${e}`),N(r*e>=0,()=>`Negative dimension size caused by overflow when multiplying + ${r} and ${e} for depthToSpace with input shape + ${s.shape}`),N(i*e>=0,()=>`Negative dimension size caused by overflow when multiplying + ${i} and ${e} for depthToSpace with input shape + ${s.shape}`),N(o%(e*e)===0,()=>`Dimension size must be evenly divisible by ${e*e} but is ${o} for depthToSpace with input shape ${s.shape}`);const a={x:s},l={blockSize:e,dataFormat:t};return ee.runKernel(D0,a,l)}const t5=ie({depthToSpace_:e5});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function n5(n,e,t,s,r="NHWC",i=[1,1],o){const a=G(n,"x","depthwiseConv2d","float32"),l=G(e,"filter","depthwiseConv2d","float32");let c=a,u=!1;a.rank===3&&(u=!0,c=se(a,[1,a.shape[0],a.shape[1],a.shape[2]])),N(c.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),N(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);const h=r==="NHWC"?c.shape[3]:c.shape[1];N(h===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${h}) must match the inChannels dimension in filter ${l.shape[2]}.`),or("depthwiseConv2d",s,o);const d={x:c,filter:l},p={strides:t,pad:s,dataFormat:r,dilations:i,dimRoundingMode:o},f=ee.runKernel(fd,d,p);return u?se(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const L2=ie({depthwiseConv2d_:n5});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function s5(n,e,t,s,r=[1,1],i="NHWC"){const o=G(n,"x","dilation2d"),a=G(e,"filter","dilation2d");N(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),N(a.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${a.rank}.`),N(i==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${i}`);let l=o,c=!1;o.rank===3&&(l=se(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=!0),N(l.shape[3]===a.shape[2],()=>`Error in dilation2d: input and filter must have the same depth: ${l.shape[3]} vs ${a.shape[2]}`);const u={x:l,filter:a},h={strides:t,pad:s,dilations:r},d=ee.runKernel(md,u,h);return c?se(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const r5=ie({dilation2d_:s5});/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oa(n,e){const t=n.length,s=[];for(let r=0;r1&&o===1&&s.unshift(i)}return s}function rs(n,e){const t=[];for(let s=0;s1)&&t.unshift(i)}return t}function pt(n,e){const t=Math.max(n.length,e.length),s=new Array(t);for(let r=0;r`Error in dot: inputs must all be rank 1 or 2, but got ranks ${t.rank} and ${s.rank}.`);const r=t.rank===1?t.size:t.shape[1],i=s.rank===1?s.size:s.shape[0];if(N(r===i,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${i}.`),t.rank===1&&s.rank===1){const o=se(t,[1,-1]),a=se(s,[-1,1]),l=Jt(o,a);return se(l,[])}else if(t.rank===1&&s.rank===2){const o=se(t,[1,-1]),a=se(s,[s.shape[0],s.shape[1]]),l=Jt(o,a);return se(l,[l.size])}else if(t.rank===2&&s.rank===1){const o=se(s,[-1,1]),a=Jt(t,o);return se(a,[a.size])}else{const o=se(s,[s.shape[0],s.shape[1]]);return Jt(t,o)}}const h5=ie({dot_:u5});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function d5(n,...e){const t=e.map((r,i)=>G(r,`tensors${i}`,"einsum")),s={equation:n};return ee.runKernel(F0,t,s)}const fh=ie({einsum_:d5});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function p5(n){const t={x:G(n,"x","elu","float32")};return ee.runKernel(cu,t)}const hm=ie({elu_:p5});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function f5(n){let e=G(n,"x","erf");N(e.dtype==="int32"||e.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),e.dtype==="int32"&&(e=qe(e,"float32"));const t={x:e};return ee.runKernel(uu,t)}const VC=ie({erf_:f5});/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function F2(n,e){for(let t=0;tn[i]);return[t,r]}function Vn(n,e){const t=e.map(s=>1);return WC(n,t,e)}function Kn(n,e,t){N(F2(e,t),()=>`${n} supports only inner-most axes for now. Got axes ${e} and rank-${t} input.`)}function ln(n,e){if(F2(n,e))return null;const t=[];for(let s=0;st.push(s)),t}function no(n){return n.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function xn(n,e){const t=[];for(let s=e-n;s"Axis must be <= rank of the tensor");const s={input:t},r={dim:e};return ee.runKernel(xd,s,r)}const js=ie({expandDims_:T5});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function I5(n){const t={x:G(n,"x","expm1")};return ee.runKernel(du,t)}const E5=ie({expm1_:I5});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function k5(n,e){const t=G(n,"x","tile","string_or_numeric");N(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of reps ${e}.`);const s={x:t},r={reps:e};return ee.runKernel(Wu,s,r)}const gi=ie({tile_:k5});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function A5(n,e,t,s="float32"){e==null&&(e=n);const r=Tt([n,e],s),i=n<=e?n:e;for(let a=0;a`Error in localResponseNormalization: x must be rank 3 or 4 but got + rank ${i.rank}.`),N(kc(e),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${e}.`);let o=i,a=!1;i.rank===3&&(a=!0,o=se(i,[1,i.shape[0],i.shape[1],i.shape[2]]));const l={x:o},c={depthRadius:e,bias:t,alpha:s,beta:r},u=ee.runKernel(Ed,l,c);return a?se(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const H5=ie({localResponseNormalization_:G5});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function q5(n){const t={x:G(n,"x","log","float32")};return ee.runKernel(yu,t)}const Zi=ie({log_:q5});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function X5(n){const t={x:G(n,"x","log1p")};return ee.runKernel(wu,t)}const qC=ie({log1p_:X5});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function K5(n,e){N(q1(n),()=>"The f passed in variableGrads(f) must be a function"),N(e==null||Array.isArray(e)&&e.every(c=>c instanceof Df),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const t=e!=null;if(!t){e=[];for(const c in ee.registeredVariables)e.push(ee.registeredVariables[c])}const s=t?e.filter(c=>!c.trainable):null,r=e.length;e=e.filter(c=>c.trainable),N(e.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);const i=!0,{value:o,grads:a}=ee.gradients(n,e,null,i);N(a.some(c=>c!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),N(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);const l={};return e.forEach((c,u)=>{a[u]!=null&&(l[c.name]=a[u])}),s?.forEach(c=>l[c.name]=null),{value:o,grads:l}}function $c(n){return ee.customGrad(n)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function j5(n){const t={x:G(n,"x","neg")};return ee.runKernel(Dd,t)}const Bn=ie({neg_:j5});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Y5(n){const t={x:G(n,"x","softplus")};return ee.runKernel(Fu,t)}const tp=ie({softplus_:Y5});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Z5(n){const e=G(n,"x","logSigmoid");return $c(s=>({value:Bn(tp(Bn(s))),gradFunc:o=>Z(o,Hu(Bn(s)))}))(e)}const J5=ie({logSigmoid_:Z5});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Q5(n,e){let t=G(n,"a","sub"),s=G(e,"b","sub");[t,s]=Un(t,s);const r={a:t,b:s};return ee.runKernel(Bu,r)}const ft=ie({sub_:Q5});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function e6(n,e=-1){const t=G(n,"logits","logSoftmax");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and axis was ${e}`);return $c((r,i)=>{const a=wi(r,e,!0),l=ft(r,a),c=ft(qe(l,"float32"),Zi(lt(Yi(l),e,!0)));return i([c]),{value:c,gradFunc:(h,d)=>{const[p]=d,f=!0,x=Yi(p);return ft(h,Z(lt(h,e,f),x))}}})(t)}const fm=ie({logSoftmax_:e6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function t6(n,e=null,t=!1){const s=G(n,"x","logSumExp"),r=It(e,s.shape),i=wi(s,r,!0),o=ft(s,i),a=Yi(o),l=lt(a,r),c=Zi(l),u=ke(se(i,c.shape),c);if(t){const h=Vn(u.shape,r);return se(u,h)}return u}const XC=ie({logSumExp_:t6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function n6(n,e){const t=G(n,"a","logicalAnd","bool"),s=G(e,"b","logicalAnd","bool");pt(t.shape,s.shape);const r={a:t,b:s};return ee.runKernel(_d,r)}const Ao=ie({logicalAnd_:n6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function s6(n){const t={x:G(n,"x","logicalNot","bool")};return ee.runKernel(Td,t)}const U2=ie({logicalNot_:s6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function r6(n,e){const t=G(n,"a","logicalOr","bool"),s=G(e,"b","logicalOr","bool");pt(t.shape,s.shape);const r={a:t,b:s};return ee.runKernel(Id,r)}const KC=ie({logicalOr_:r6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function i6(n,e){const t=G(n,"a","logicalXor","bool"),s=G(e,"b","logicalXor","bool");return pt(t.shape,s.shape),Ao(KC(n,e),U2(Ao(n,e)))}const o6=ie({logicalXor_:i6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a6(n,e,t,s,r){const i=G(n,"x","maxPool"),o=1;let a=i,l=!1;i.rank===3&&(l=!0,a=se(i,[1,i.shape[0],i.shape[1],i.shape[2]])),N(a.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.rank}.`),N(gs(t,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${o}'`),or("maxPool",s,r);const c={x:a},u={filterSize:e,strides:t,pad:s,dimRoundingMode:r},h=ee.runKernel(Ad,c,u);return l?se(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const V2=ie({maxPool_:a6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function l6(n,e=[1,1,1],t,s,r,i="NDHWC"){const o=G(n,"x","maxPool3d");let a=o,l=!1;o.rank===4&&(l=!0,a=se(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),N(a.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${a.rank}.`),N(i==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${i}`),or("maxPool3d",s,r);const c={x:a},u={filterSize:e,strides:t,pad:s,dimRoundingMode:r,dataFormat:i},h=ee.runKernel(Rd,c,u);return l?se(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}const c6=ie({maxPool3d_:l6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function u6(n,e){let t=G(n,"a","maximum"),s=G(e,"b","maximum");[t,s]=Un(t,s),t.dtype==="bool"&&(t=qe(t,"int32"),s=qe(s,"int32")),pt(t.shape,s.shape);const r={a:t,b:s};return ee.runKernel(Su,r)}const Ca=ie({maximum_:u6});/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function h6(n,e=null,t=!1){const r={x:G(n,"x","mean")},i={axis:e,keepDims:t};return ee.runKernel(Md,r,i)}const Xn=ie({mean_:h6});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function On(n,e="float32"){if(No(n),e==="complex64"){const s=On(n,"float32"),r=On(n,"float32");return Mc(s,r)}const t=Cs(re(n),e);return ee.makeTensor(t,n,e)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _a(n,e="float32"){if(No(n),e==="complex64"){const s=_a(n,"float32"),r=On(n,"float32");return Mc(s,r)}const t=o2(re(n),e);return ee.makeTensor(t,n,e)}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function d6(n,e){let t=G(n,"a","minimum"),s=G(e,"b","minimum");[t,s]=Un(t,s),t.dtype==="bool"&&(t=qe(t,"int32"),s=qe(s,"int32")),pt(t.shape,s.shape);const r={a:t,b:s};return ee.runKernel(Cu,r)}const Bh=ie({minimum_:d6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function p6(n,e,t){N(t==="reflect"||t==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${t}.`);const s=G(n,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");N(e.length===s.rank,()=>`Padding doesn't match input. Must be ${s.rank}. Got ${e.length}.`);const r=t==="reflect"?1:0;for(let a=0;a"Invalid number of paddings. Must be length of 2 each."),N(e[a][0]>=0&&e[a][0]<=s.shape[a]-r&&e[a][1]>=0&&e[a][1]<=s.shape[a]-r,()=>`Padding in dimension ${a} cannot be greater than or equal to ${s.shape[a]-r} or less than 0 for input of shape ${s.shape}`);const i={paddings:e,mode:t},o={x:s};return ee.runKernel($d,o,i)}const f6=ie({mirrorPad_:p6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function m6(n,e){let t=G(n,"a","mod"),s=G(e,"b","mod");[t,s]=Un(t,s);const r={a:t,b:s};return ee.runKernel(_u,r)}const g6=ie({mod_:m6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function x6(n,e=null,t=!1){n=G(n,"x","moments");const s=It(e,n.shape),r=Xn(n,s,t);let i=r.shape;t||(i=Vn(r.shape,s));const o=yn(ft(qe(n,"float32"),se(r,i))),a=Xn(o,s,t);return{mean:r,variance:a}}const W2=ie({moments_:x6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function v6(n,e){let t=G(n,"a","notEqual","string_or_numeric"),s=G(e,"b","notEqual","string_or_numeric");[t,s]=Un(t,s),pt(t.shape,s.shape);const r={a:t,b:s};return ee.runKernel(Pd,r)}const Ff=ie({notEqual_:v6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function b6(n,e,t=1,s=0,r="int32"){if(e<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${e}`);const o={indices:G(n,"indices","oneHot","int32")},a={dtype:r,depth:e,onValue:t,offValue:s};return ee.runKernel(Fd,o,a)}const jC=ie({oneHot_:b6});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function y6(n){const t={x:G(n,"x","onesLike")};return ee.runKernel(Ld,t)}const ti=ie({onesLike_:y6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function w6(n,e,t=0){const s=G(n,"x","pad");if(s.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const r={paddings:e,constantValue:t},i={x:s};return ee.runKernel(zd,i,r)}const G2=ie({pad_:w6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function S6(n,e,t){const s=G(n,"x","spaceToBatchND");N(s.rank>=1+e.length,()=>`input rank ${s.rank} should be > than [blockShape] ${e.length}`),N(t.length===e.length,()=>`paddings.shape[0] ${t.length} must be equal to [blockShape] ${e.length}`),N(s.shape.reduce((o,a,l)=>l>0&&l<=e.length?o&&(a+t[l-1][0]+t[l-1][1])%e[l-1]===0:o,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${t.toString()} must be divisible by blockShapes ${e.toString()}`);const r={x:s},i={blockShape:e,paddings:t};return ee.runKernel(jd,r,i)}const H2=ie({spaceToBatchND_:S6});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function C6(n,e,t,s,r,i,o){r==null&&(r=[1,1]),i==null&&(i=1),s===0&&(s="valid");const a=G(n,"x","maxPool");let l=a,c=!1;a.rank===3&&(c=!0,l=se(a,[1,a.shape[0],a.shape[1],a.shape[2]])),N(gs(i,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${i} and dilations '${r}'`);const u=Rs(l.shape,e,i,r,s),h=[u.dilationHeight,u.dilationWidth];let d;s==="same"?d=T6([u.filterHeight,u.filterWidth],h):d=[[0,0],[0,0]];const p=h[0]===1&&h[1]===1,[f,x]=_6([u.inHeight,u.inWidth],h,d),m=p?s:"valid",g=p?l:H2(l,h,f),b=(t==="avg"?()=>N2(g,e,i,m,o):()=>V2(g,e,i,m,o))(),y=p?b:$2(b,h,x);return c?se(y,[y.shape[1],y.shape[2],y.shape[3]]):y}function _6(n,e,t){const s=t.map(u=>u[0]),r=t.map(u=>u[1]),i=n.concat(s,r),o=e.map((u,h)=>(u-i[h]%u)%u),a=r.map((u,h)=>u+o[h]),l=e.map((u,h)=>[s[h],a[h]]),c=e.map((u,h)=>[0,o[h]]);return[l,c]}function T6(n,e){const s=n.map((o,a)=>o+(o-1)*(e[a]-1)).map(o=>o-1),r=s.map(o=>Math.floor(o/2)),i=s.map((o,a)=>o-r[a]);return s.map((o,a)=>[r[a],i[a]])}const I6=ie({pool_:C6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function E6(n,e){const t=G(n,"x","prelu"),s=G(e,"alpha","prelu"),r={x:t,alpha:s};return ee.runKernel(Bd,r)}const q2=ie({prelu_:E6});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function k6(n,e=null,t=!1){let s=G(n,"x","prod");s.dtype==="bool"&&(s=qe(s,"int32"));const r={x:s},i={axis:e,keepDims:t};return ee.runKernel(Ud,r,i)}const A6=ie({prod_:k6});var X2={exports:{}};X2.exports;(function(n){(function(e,t,s){function r(l){var c=this,u=a();c.next=function(){var h=2091639*c.s0+c.c*23283064365386963e-26;return c.s0=c.s1,c.s1=c.s2,c.s2=h-(c.c=h|0)},c.c=1,c.s0=u(" "),c.s1=u(" "),c.s2=u(" "),c.s0-=u(l),c.s0<0&&(c.s0+=1),c.s1-=u(l),c.s1<0&&(c.s1+=1),c.s2-=u(l),c.s2<0&&(c.s2+=1),u=null}function i(l,c){return c.c=l.c,c.s0=l.s0,c.s1=l.s1,c.s2=l.s2,c}function o(l,c){var u=new r(l),h=c&&c.state,d=u.next;return d.int32=function(){return u.next()*4294967296|0},d.double=function(){return d()+(d()*2097152|0)*11102230246251565e-32},d.quick=d,h&&(typeof h=="object"&&i(h,u),d.state=function(){return i(u,{})}),d}function a(){var l=4022871197,c=function(u){u=String(u);for(var h=0;h>>0,d-=l,d*=l,l=d>>>0,d-=l,l+=d*4294967296}return(l>>>0)*23283064365386963e-26};return c}t&&t.exports?t.exports=o:this.alea=o})(kl,n)})(X2);var R6=X2.exports,K2={exports:{}};K2.exports;(function(n){(function(e,t,s){function r(a){var l=this,c="";l.x=0,l.y=0,l.z=0,l.w=0,l.next=function(){var h=l.x^l.x<<11;return l.x=l.y,l.y=l.z,l.z=l.w,l.w^=l.w>>>19^h^h>>>8},a===(a|0)?l.x=a:c+=a;for(var u=0;u>>0)/4294967296};return h.double=function(){do var d=c.next()>>>11,p=(c.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=c.next,h.quick=h,u&&(typeof u=="object"&&i(u,c),h.state=function(){return i(c,{})}),h}t&&t.exports?t.exports=o:this.xor128=o})(kl,n)})(K2);var M6=K2.exports,j2={exports:{}};j2.exports;(function(n){(function(e,t,s){function r(a){var l=this,c="";l.next=function(){var h=l.x^l.x>>>2;return l.x=l.y,l.y=l.z,l.z=l.w,l.w=l.v,(l.d=l.d+362437|0)+(l.v=l.v^l.v<<4^(h^h<<1))|0},l.x=0,l.y=0,l.z=0,l.w=0,l.v=0,a===(a|0)?l.x=a:c+=a;for(var u=0;u>>4),l.next()}function i(a,l){return l.x=a.x,l.y=a.y,l.z=a.z,l.w=a.w,l.v=a.v,l.d=a.d,l}function o(a,l){var c=new r(a),u=l&&l.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var d=c.next()>>>11,p=(c.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=c.next,h.quick=h,u&&(typeof u=="object"&&i(u,c),h.state=function(){return i(c,{})}),h}t&&t.exports?t.exports=o:this.xorwow=o})(kl,n)})(j2);var N6=j2.exports,Y2={exports:{}};Y2.exports;(function(n){(function(e,t,s){function r(a){var l=this;l.next=function(){var u=l.x,h=l.i,d,p;return d=u[h],d^=d>>>7,p=d^d<<24,d=u[h+1&7],p^=d^d>>>10,d=u[h+3&7],p^=d^d>>>3,d=u[h+4&7],p^=d^d<<7,d=u[h+7&7],d=d^d<<13,p^=d^d<<9,u[h]=p,l.i=h+1&7,p};function c(u,h){var d,p=[];if(h===(h|0))p[0]=h;else for(h=""+h,d=0;d0;--d)u.next()}c(l,a)}function i(a,l){return l.x=a.x.slice(),l.i=a.i,l}function o(a,l){a==null&&(a=+new Date);var c=new r(a),u=l&&l.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var d=c.next()>>>11,p=(c.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=c.next,h.quick=h,u&&(u.x&&i(u,c),h.state=function(){return i(c,{})}),h}t&&t.exports?t.exports=o:this.xorshift7=o})(kl,n)})(Y2);var $6=Y2.exports,Z2={exports:{}};Z2.exports;(function(n){(function(e,t,s){function r(a){var l=this;l.next=function(){var u=l.w,h=l.X,d=l.i,p,f;return l.w=u=u+1640531527|0,f=h[d+34&127],p=h[d=d+1&127],f^=f<<13,p^=p<<17,f^=f>>>15,p^=p>>>12,f=h[d]=f^p,l.i=d,f+(u^u>>>16)|0};function c(u,h){var d,p,f,x,m,g=[],v=128;for(h===(h|0)?(p=h,h=null):(h=h+"\0",p=0,v=Math.max(v,h.length)),f=0,x=-32;x>>15,p^=p<<4,p^=p>>>13,x>=0&&(m=m+1640531527|0,d=g[x&127]^=p+m,f=d==0?f+1:0);for(f>=128&&(g[(h&&h.length||0)&127]=-1),f=127,x=4*128;x>0;--x)p=g[f+34&127],d=g[f=f+1&127],p^=p<<13,d^=d<<17,p^=p>>>15,d^=d>>>12,g[f]=p^d;u.w=m,u.X=g,u.i=f}c(l,a)}function i(a,l){return l.i=a.i,l.w=a.w,l.X=a.X.slice(),l}function o(a,l){a==null&&(a=+new Date);var c=new r(a),u=l&&l.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var d=c.next()>>>11,p=(c.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=c.next,h.quick=h,u&&(u.X&&i(u,c),h.state=function(){return i(c,{})}),h}t&&t.exports?t.exports=o:this.xor4096=o})(kl,n)})(Z2);var D6=Z2.exports,J2={exports:{}};J2.exports;(function(n){(function(e,t,s){function r(a){var l=this,c="";l.next=function(){var h=l.b,d=l.c,p=l.d,f=l.a;return h=h<<25^h>>>7^d,d=d-p|0,p=p<<24^p>>>8^f,f=f-h|0,l.b=h=h<<20^h>>>12^d,l.c=d=d-p|0,l.d=p<<16^d>>>16^f,l.a=f-h|0},l.a=0,l.b=0,l.c=-1640531527,l.d=1367130551,a===Math.floor(a)?(l.a=a/4294967296|0,l.b=a|0):c+=a;for(var u=0;u>>0)/4294967296};return h.double=function(){do var d=c.next()>>>11,p=(c.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=c.next,h.quick=h,u&&(typeof u=="object"&&i(u,c),h.state=function(){return i(c,{})}),h}t&&t.exports?t.exports=o:this.tychei=o})(kl,n)})(J2);var P6=J2.exports,YC={exports:{}};const L6={},F6=Object.freeze(Object.defineProperty({__proto__:null,default:L6},Symbol.toStringTag,{value:"Module"})),O6=LR(F6);(function(n){(function(e,t,s){var r=256,i=6,o=52,a="random",l=s.pow(r,i),c=s.pow(2,o),u=c*2,h=r-1,d;function p(y,w,C){var T=[];w=w==!0?{entropy:!0}:w||{};var E=g(m(w.entropy?[y,b(t)]:y??v(),3),T),R=new f(T),_=function(){for(var k=R.g(i),F=l,B=0;k=u;)k/=2,F/=2,B>>>=1;return(k+B)/F};return _.int32=function(){return R.g(4)|0},_.quick=function(){return R.g(4)/4294967296},_.double=_,g(b(R.S),t),(w.pass||C||function(k,F,B,M){return M&&(M.S&&x(M,R),k.state=function(){return x(R,{})}),B?(s[a]=k,F):k})(_,E,"global"in w?w.global:this==s,w.state)}function f(y){var w,C=y.length,T=this,E=0,R=T.i=T.j=0,_=T.S=[];for(C||(y=[C++]);E=1||o===0);const a=Math.sqrt(-2*Math.log(o)/o);e=this.mean+this.stdDev*r*a,t=this.mean+this.stdDev*i*a,(!this.truncated||this.isValidTruncated(e))&&(s=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class q6{constructor(e=0,t=1,s,r){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=s,r==null&&(r=Math.random()),typeof r=="number"&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=Q2.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function X6(n,e=0,t=1,s,r){if(No(n),s!=null&&s==="bool")throw new Error(`Unsupported data type ${s}`);const i=new ZC(e,t,s,!1,r),o=Tt(n,s);for(let a=0;a`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),N(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),N(c.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),N(c.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),N(c.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);const d=l.shape[2],p=l.shape[3];N(c.shape[2]===d*p,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${d*p}, but got ${c.shape[2]}.`);const f=L2(u,l,s,r,o,i),m=gl(f,c,1,"valid",o);return h?se(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const n4=ie({separableConv2d_:i$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function o$(n){const t={x:G(n,"x","sign")};return ee.runKernel(Pu,t)}const a$=ie({sign_:o$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function l$(n){const t={x:G(n,"x","sin","float32")};return ee.runKernel($u,t)}const s4=ie({sin_:l$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function c$(n){const t={x:G(n,"x","sinh")};return ee.runKernel(Du,t)}const r4=ie({sinh_:c$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function u$(n,e,t){const s=G(n,"x","slice1d");return N(s.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),fn(s,[e],[t])}const ev=ie({slice1d_:u$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function h$(n,e,t){const s=G(n,"x","slice2d");return N(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),fn(s,e,t)}const i4=ie({slice2d_:h$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function d$(n,e,t){const s=G(n,"x","slice3d");return N(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),fn(s,e,t)}const tv=ie({slice3d_:d$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function p$(n,e,t){const s=G(n,"x","slice4d");return N(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),fn(s,e,t)}const zf=ie({slice4d_:p$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function f$(n,e=-1){const t=G(n,"logits","softmax","float32");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and dim was ${e}`);const s={logits:t},r={dim:e};return ee.runKernel(Zd,s,r)}const np=ie({softmax_:f$});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function m$(n){N(n.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${n.dtype}.`);const e={input:n};return ee.runKernel(z0,e)}const o4=ie({fft_:m$});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function g$(n){N(n.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${n.dtype}.`);const e={input:n};return ee.runKernel(V0,e)}const lx=ie({ifft_:g$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function x$(n){const e=n.shape[n.shape.length-1],t=n.size/e;let s;if(e<=2){const r=se(n,[t,e]);s=lx(r)}else{const r=[t,2*(e-1)],i=se(Of(n),[t,e]),o=se(z2(n),[t,e]),a=vl(fn(i,[0,1],[t,e-2]),1),l=Z(vl(fn(o,[0,1],[t,e-2]),1),Ht(-1)),c=tr([i,a],1),u=tr([o,l],1),h=se(Mc(c,u),[r[0],r[1]]);s=lx(h)}if(s=Of(s),n.rank===3&&n.shape[0]!==0){const r=s,i=n.shape[0];s=se(s,[i,s.shape[0]/i,s.shape[1]]),r.dispose()}return s}const v$=ie({irfft_:x$});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function b$(n,e,t=0){const r={x:G(n,"x","split")},i={numOrSizeSplits:e,axis:t};return ee.runKernel(Yd,r,i)}const kr=ie({split_:b$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function y$(n,e){N(n.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${n.dtype}`);let t=n.shape[n.shape.length-1];const s=n.size/t;let r;if(e!=null&&e0),x=n.shape.map(m=>m);x[n.shape.length-1]=e,r=fn(n,f,x),t=e}else if(e!=null&&e>t){const f=n.shape.map(x=>x);f[n.shape.length-1]=e-t,r=tr([n,On(f)],n.shape.length-1),t=e}else r=n;const i=Xt(r),o=se(Mc(r,i),[s,t]),a=o4(o),l=Math.floor(t/2)+1,c=Of(a),u=z2(a),h=kr(c,[l,t-l],c.shape.length-1),d=kr(u,[l,t-l],u.shape.length-1),p=r.shape.slice();return p[r.shape.length-1]=l,se(Mc(h[0],d[0]),p)}const w$=ie({rfft_:y$});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function S$(n,e){let t=G(n,"a","squaredDifference"),s=G(e,"b","squaredDifference");[t,s]=Un(t,s),pt(t.shape,s.shape);const r={a:t,b:s},i={};return ee.runKernel(zu,r,i)}const C$=ie({squaredDifference_:S$});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _$(n,e){const t=G(n,"x","squeeze","string_or_numeric");return se(t,ba(t.shape,e).newShape)}const sp=ie({squeeze_:_$});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function T$(n,e=0){const t=IC(n,"tensors","stack","string_or_numeric");N(t.length>=1,()=>"Pass at least one tensor to tf.stack"),t.length>0&&N(e<=t[0].rank,()=>"Axis must be <= rank of the tensor");const s=t,r={axis:e};return ee.runKernel(Od,s,r)}const Ji=ie({stack_:T$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function I$(n,e=0){const s={x:G(n,"x","step")},r={alpha:e};return ee.runKernel(Gu,s,r)}const rp=ie({step_:I$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function E$(n,e,t,s,r=0,i=0,o=0,a=0,l=0){const u={x:G(n,"x","stridedSlice","string_or_numeric")},h={begin:e,end:t,strides:s,beginMask:r,endMask:i,ellipsisMask:o,newAxisMask:a,shrinkAxisMask:l};return ee.runKernel(em,u,h)}const k$=ie({stridedSlice_:E$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function A$(n){const t={x:G(n,"x","tan","float32")};return ee.runKernel(Uu,t)}const R$=ie({tan_:A$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Zs(n,e){XS(n);const t=om(n,e);if(t.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return am(n,null,t,e)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Rg(n,e,t){if(XS(n),e!=null&&e.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const s=om(n,t);if(s.length!==2&&s.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(s.length===1&&e==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return am(n,e,s,t)}function so(n,e,t){const s=e.shape.length,r=s>1?e.shape[s-1]:1,i=t.length;let o=1;for(let h=r;h= 0 but got ${e}`);if(e>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${e}`);const i={x:s},o={k:e,sorted:t},[a,l]=ee.runKernel(tm,i,o);return{values:a,indices:l}}const N$=ie({topk_:M$});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $$(n,e=0,t=1,s,r){if(No(n),s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");const i=new ZC(e,t,s,!0,r),o=Tt(n,s);for(let a=0;a0,()=>"The input tensor must be at least 1D");const s={x:t},r={axis:e},[i,o]=ee.runKernel(T2,s,r);return{values:i,indices:o}}const P$=ie({unique_:D$});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function L$(n,e,t){const s=G(n,"x","unsortedSegmentSum"),r=G(e,"segmentIds","unsortedSegmentSum","int32");N(kc(t),()=>"numSegments must be of dtype int");const i={x:s,segmentIds:r},o={numSegments:t};return ee.runKernel(Qd,i,o)}const l4=ie({unsortedSegmentSum_:L$});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function F$(n,e=0){const t=G(n,"x","unstack","string_or_numeric");N(e>=-t.shape.length&&e`Axis = ${e} is not in [-${t.shape.length}, ${t.shape.length})`);const s={value:t},r={axis:e};return ee.runKernel(Jd,s,r)}const bl=ie({unstack_:F$});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function tl(n,e=!0,t,s){return ee.makeVariable(n,e,t,s)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function c4(n,e){const t=[];for(let i=0;ia).reverse()),N(s.rank===e.length,()=>`Error in transpose: rank of input ${s.rank} must match length of perm ${e}.`),e.forEach(o=>{N(o>=0&&o`All entries in 'perm' must be between 0 and ${s.rank-1} but got ${e}`)}),s.rank<=1)return s.clone();const r={x:s},i={perm:e};return s.dtype==="complex64"?le(()=>{let o=Of(s),a=z2(s);return o=ee.runKernel(rl,{x:o},i),a=ee.runKernel(rl,{x:a},i),t&&(a=Bn(a)),Mc(o,a)}):ee.runKernel(rl,r,i)}const qt=ie({transpose_:O$});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function z$(n,e){if(e==null)return n.shape.slice();if(Wt(n.shape,e))return e;if(n.shape.length===e.length){const t=[];for(let s=0;s`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`),N(e>=0&&e<1,()=>`rate must be a float in the range [0, 1), but got ${e}.`),e===0)return n instanceof Yn?r.clone():r;const i=z$(r,t),o=1-e,a=ut(pm(ke(aa(i,0,1,"float32",s),o)),o);return Z(r,a)}const U$=ie({dropout_:B$});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function V$(n,e,t,s,r,i="NHWC",o){let a=n;n.rank===3&&(a=se(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let l=e;l.rank===3&&(l=se(e,[1,e.shape[0],e.shape[1],e.shape[2]])),N(a.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${a.shape}.`),N(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),N(t.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${t}.`);const c=i==="NHWC"?a.shape[3]:a.shape[1],u=i==="NHWC"?l.shape[3]:l.shape[1];N(c===t[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${t[2]}.`),N(u===t[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${t[3]}).`),or("conv2dDerFilter",r,o);const h={x:a,dy:l},d={strides:s,pad:r,dataFormat:i,dimRoundingMode:o,filterShape:t};return ee.runKernel(k0,h,d)}const nv=ie({conv2DBackpropFilter_:V$});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sv(n,e,t){if(t==null||t==="linear")return n;if(t==="relu")return Z(n,rp(e));throw new Error(`Cannot compute gradient for fused activation ${t}.`)}function rv(n,e){let t=e;const s=rs(n.shape,e.shape);return s.length>0&&(t=lt(t,s)),se(t,n.shape)}function iv(n,e,t,s){if(e==="linear")return n;if(e==="relu")return $l(n);if(e==="elu")return hm(n);if(e==="relu6")return JC(n);if(e==="prelu")return q2(n,t);if(e==="leakyrelu")return B2(n,s);if(e==="sigmoid")return Hu(n);throw new Error(`Unknown fused activation ${e}.`)}const ov=(n,e)=>!(n>0)||e==="linear";/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function W$({x:n,filter:e,strides:t,pad:s,dataFormat:r="NHWC",dilations:i=[1,1],dimRoundingMode:o,bias:a,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(l=l||"linear",ov(ee.state.gradientDepth,l)===!1){N(r==="NHWC",()=>`Error in fused conv2d: got dataFormat of ${r} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let C=gl(n,e,t,s,r,i,o);return a!=null&&(C=ke(C,a)),iv(C,l,c,u)}const h=G(n,"x","conv2d","float32"),d=G(e,"filter","conv2d","float32");let p=h,f=!1;h.rank===3&&(f=!0,p=se(h,[1,h.shape[0],h.shape[1],h.shape[2]])),N(p.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${p.rank}.`),N(d.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${d.rank}.`),or("fused conv2d",s,o);const x=r==="NHWC"?p.shape[3]:p.shape[1];N(d.shape[2]===x,()=>`Error in conv2d: depth of input (${x}) must match input depth for filter ${d.shape[2]}.`),N(gs(t,i),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${i}'`);const m=Cn(p.shape,d.shape,t,i,s,o);let g;a!=null&&(g=G(a,"bias","fused conv2d"),[g]=Un(g,h),r==="NHWC"?pt(m.outShape,g.shape):(N(g.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${g.shape.length}.`),N(g.shape.length===0||g.shape[0]===m.outChannels||g.shape[0]===1,()=>`Error in fused conv2d: bias shape (${g.shape}) is not compatible with the number of output channels (${m.outChannels})`)));let v;if(c!=null){const C=c.shape;if(N(C.length<=1||C.length===3,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${C.length}.`),C.length===1)N(C[0]===1||C[0]===m.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${C}) is not compatible with the number of output channels (${m.outChannels}).`);else if(C.length===3)try{pt(C,m.outShape)}catch{const E=`Error in fused conv2d: PReLU activation weights (${C}) is not compatible with the output shape of the conv2d (${m.outShape}).`;throw Error(E)}v=G(c,"prelu weights","fused conv2d")}const b=(C,T)=>{N(r==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${r} but only NHWC is currently supported.`);const[E,R,_,k]=T,F=sv(C,_,l);N(fl(i),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${i}'`);const B=D2(R.shape,F,E,t,s),M=nv(R,F,E.shape,t,s),P=[B,M];if(k!=null){const L=rv(k,F);P.push(L)}return P},y={x:p,filter:d,bias:g,preluActivationWeights:v},w={strides:t,pad:s,dataFormat:r,dilations:i,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return a==null?$c((T,E,R)=>{let _=ee.runKernel(Lh,y,w);return R([E,T,_]),f&&(_=se(_,[_.shape[1],_.shape[2],_.shape[3]])),{value:_,gradFunc:b}})(p,d):$c((T,E,R,_)=>{let k=ee.runKernel(Lh,y,w);return _([E,T,k,R]),f&&(k=se(k,[k.shape[1],k.shape[2],k.shape[3]])),{value:k,gradFunc:b}})(p,d,g)}const G$=ie({fusedConv2d_:W$});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function H$(n,e,t,s,r,i=[1,1],o){let a=n;n.rank===3&&(a=se(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let l=e;l.rank===3&&(l=se(e,[1,e.shape[0],e.shape[1],e.shape[2]]));const c={x:a,dy:l},u={strides:s,pad:r,dimRoundingMode:o,dilations:i,filterShape:t};return ee.runKernel(P0,c,u)}const q$=ie({depthwiseConv2dNativeBackpropFilter_:H$});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function X$(n,e,t,s,r,i=[1,1],o){let a=e,l=!1;e.rank===3&&(l=!0,a=se(e,[1,e.shape[0],e.shape[1],e.shape[2]]));const c={dy:a,filter:t},u={strides:s,pad:r,dimRoundingMode:o,dilations:i,inputShape:n},h=ee.runKernel(L0,c,u);return l?se(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const K$=ie({depthwiseConv2dNativeBackpropInput_:X$});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function j$({a:n,b:e,transposeA:t=!1,transposeB:s=!1,bias:r,activation:i="linear",preluActivationWeights:o,leakyreluAlpha:a=.2}){if(ov(ee.state.gradientDepth,i)===!1){let k=Jt(n,e,t,s);return r!=null&&(k=ke(k,r)),iv(k,i,o,a)}let l=G(n,"a","fused matMul"),c=G(e,"b","fused matMul");[l,c]=Un(l,c);const u=t?l.shape[l.rank-2]:l.shape[l.rank-1],h=s?c.shape[c.rank-1]:c.shape[c.rank-2],d=t?l.shape[l.rank-1]:l.shape[l.rank-2],p=s?c.shape[c.rank-2]:c.shape[c.rank-1],f=l.shape.slice(0,-2),x=c.shape.slice(0,-2),m=re(f),g=re(x);N(u===h,()=>`Error in fused matMul: inner shapes (${u}) and (${h}) of Tensors with shapes ${l.shape} and ${c.shape} and transposeA=${t} and transposeB=${s} must match.`);const b=pt(l.shape.slice(0,-2),c.shape.slice(0,-2)).concat([d,p]),y=t?se(l,[m,u,d]):se(l,[m,d,u]),w=s?se(c,[g,p,h]):se(c,[g,h,p]);let C;r!=null&&(C=G(r,"bias","fused matMul"),[C]=Un(C,l),pt(b,C.shape));let T;o!=null&&(T=G(o,"prelu weights","fused matMul"));const E=(k,F)=>{const[B,M,P,L]=F,q=sv(se(k,P.shape),P,i);let U,X;if(!t&&!s?(U=Jt(q,M,!1,!0),X=Jt(B,q,!0,!1)):!t&&s?(U=Jt(q,M,!1,!1),X=Jt(q,B,!0,!1)):t&&!s?(U=Jt(M,q,!1,!0),X=Jt(B,q,!1,!1)):(U=Jt(M,q,!0,!0),X=Jt(q,B,!0,!0)),r!=null){const K=rv(L,q);return[U,X,K]}else return[U,X]},R={a:y,b:w,bias:C,preluActivationWeights:T},_={transposeA:t,transposeB:s,activation:i,leakyreluAlpha:a};return r==null?$c((F,B,M)=>{const P=ee.runKernel(Ph,R,_);return M([F,B,P]),{value:se(P,b),gradFunc:E}})(y,w):$c((F,B,M,P)=>{const L=ee.runKernel(Ph,R,_);return P([F,B,L,M]),{value:se(L,b),gradFunc:E}})(y,w,C)}const iy=ie({fusedMatMul_:j$});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Y$(n,e,t,s,r="bilinear",i=0){const o=G(n,"image","cropAndResize"),a=G(e,"boxes","cropAndResize","float32"),l=G(t,"boxInd","cropAndResize","int32"),c=a.shape[0];N(o.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),N(a.rank===2&&a.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${a.shape}.`),N(l.rank===1&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${a.shape}.`),N(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),N(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),N(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);const u={image:o,boxes:a,boxInd:l},h={method:r,extrapolationValue:i,cropSize:s};return ee.runKernel(N0,u,h)}const Z$=ie({cropAndResize_:Y$});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function J$(n){const e=G(n,"image","flipLeftRight","float32");N(e.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${e.rank}.`);const t={image:e};return ee.runKernel(U0,t,{})}const Q$=ie({flipLeftRight_:J$});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function eD(n){const e=G(n,"image","grayscaleToRGB"),t=e.rank-1,s=e.shape[t];N(e.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${e.rank}.`),N(s===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`);const r=new Array(e.rank);return r.fill(1,0,t),r[t]=3,gi(e,r)}const tD=ie({grayscaleToRGB_:eD});/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nD(n){const e=G(n,"image","RGBToGrayscale"),t=e.rank-1,s=e.shape[t];N(e.rank>=2,()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${e.rank}.`),N(s===3,()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${s}.`);const r=e.dtype,i=qe(e,"float32"),o=Zs([.2989,.587,.114]);let a;switch(e.rank){case 2:a=fh("ij,j->i",i,o);break;case 3:a=fh("ijk,k->ij",i,o);break;case 4:a=fh("ijkl,l->ijk",i,o);break;case 5:a=fh("ijklm,m->ijkl",i,o);break;case 6:a=fh("ijklmn,n->ijklm",i,o);break;default:throw new Error("Not a valid tensor rank.")}return a=js(a,-1),qe(a,r)}const sD=ie({rgbToGrayscale_:nD});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rD(n,e,t=0,s=.5){const r=G(n,"image","rotateWithOffset","float32");N(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);const i={image:r},o={radians:e,fillValue:t,center:s};return ee.runKernel(sm,i,o)}const iD=ie({rotateWithOffset_:rD});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Xu(n,e,t,s,r,i){s==null&&(s=.5),r==null&&(r=Number.NEGATIVE_INFINITY),i==null&&(i=0);const o=n.shape[0];return t=Math.min(t,o),N(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),N(n.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${n.rank}'`),N(n.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${n.shape[1]}`),N(e.rank===1,()=>"scores must be a 1D tensor"),N(e.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${e.shape[0]}`),N(0<=i&&i<=1,()=>`softNmsSigma must be in [0, 1], but was '${i}'`),{maxOutputSize:t,iouThreshold:s,scoreThreshold:r,softNmsSigma:i}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oD(n,e,t,s=.5,r=Number.NEGATIVE_INFINITY){const i=G(n,"boxes","nonMaxSuppression","float32"),o=G(e,"scores","nonMaxSuppression","float32"),a=Xu(i,o,t,s,r);t=a.maxOutputSize,s=a.iouThreshold,r=a.scoreThreshold;const l={maxOutputSize:t,iouThreshold:s,scoreThreshold:r};return ee.runKernel(X0,{boxes:i,scores:o},l)}const aD=ie({nonMaxSuppression_:oD});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lD(n,e,t){const s=cD(n,e,t),r=s<0?-(s+1):s;n.splice(r,0,e)}function cD(n,e,t){return hD(n,e,t||uD)}function uD(n,e){return n>e?1:n>>1);const a=t(e,n[i]);a>0?s=i+1:(r=i,o=!a)}return o?s:-s-1}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mm(n,e,t,s,r){return lv(n,e,t,s,r,0)}function av(n,e,t,s,r,i){return lv(n,e,t,s,r,0,!1,i,!0)}function gm(n,e,t,s,r,i){return lv(n,e,t,s,r,i,!0)}function lv(n,e,t,s,r,i,o=!1,a=!1,l=!1){const c=[];for(let m=0;mr&&c.push({score:e[m],boxIndex:m,suppressBeginIndex:0});c.sort(oy);const u=i>0?-.5/i:0,h=[],d=[];for(;h.length0;){const m=c.pop(),{score:g,boxIndex:v,suppressBeginIndex:b}=m;if(g=b;--w){const C=dD(n,v,h[w]);if(C>=s){y=!0;break}if(m.score=m.score*pD(s,u,C),m.score<=r)break}m.suppressBeginIndex=h.length,y||(m.score===g?(h.push(v),d.push(m.score)):m.score>r&&lD(c,m,oy))}const p=h.length,f=t-p;a&&f>0&&(h.push(...new Array(f).fill(0)),d.push(...new Array(f).fill(0)));const x={selectedIndices:h};return o&&(x.selectedScores=d),l&&(x.validOutputs=p),x}function dD(n,e,t){const s=n.subarray(e*4,e*4+4),r=n.subarray(t*4,t*4+4),i=Math.min(s[0],s[2]),o=Math.min(s[1],s[3]),a=Math.max(s[0],s[2]),l=Math.max(s[1],s[3]),c=Math.min(r[0],r[2]),u=Math.min(r[1],r[3]),h=Math.max(r[0],r[2]),d=Math.max(r[1],r[3]),p=(a-i)*(l-o),f=(h-c)*(d-u);if(p<=0||f<=0)return 0;const x=Math.max(i,c),m=Math.max(o,u),g=Math.min(a,h),v=Math.min(l,d),b=Math.max(g-x,0)*Math.max(v-m,0);return b/(p+f-b)}function pD(n,e,t){const s=Math.exp(e*t*t);return t<=n?s:0}function oy(n,e){return n.score-e.score||n.score===e.score&&e.boxIndex-n.boxIndex}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function fD(n,e,t,s=.5,r=Number.NEGATIVE_INFINITY){const i=G(n,"boxes","nonMaxSuppressionAsync"),o=G(e,"scores","nonMaxSuppressionAsync"),a=Xu(i,o,t,s,r);t=a.maxOutputSize,s=a.iouThreshold,r=a.scoreThreshold;const l=await Promise.all([i.data(),o.data()]),c=l[0],u=l[1],{selectedIndices:h}=mm(c,u,t,s,r);return i!==n&&i.dispose(),o!==e&&o.dispose(),Zs(h,"int32")}const mD=fD;/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gD(n,e,t,s=.5,r=Number.NEGATIVE_INFINITY,i=0){const o=G(n,"boxes","nonMaxSuppression"),a=G(e,"scores","nonMaxSuppression"),l=Xu(o,a,t,s,r,i);t=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,i=l.softNmsSigma;const c={boxes:o,scores:a},u={maxOutputSize:t,iouThreshold:s,scoreThreshold:r,softNmsSigma:i},h=ee.runKernel(K0,c,u);return{selectedIndices:h[0],selectedScores:h[1]}}const xD=ie({nonMaxSuppressionWithScore_:gD});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function vD(n,e,t,s=.5,r=Number.NEGATIVE_INFINITY,i=0){const o=G(n,"boxes","nonMaxSuppressionAsync"),a=G(e,"scores","nonMaxSuppressionAsync"),l=Xu(o,a,t,s,r,i);t=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,i=l.softNmsSigma;const c=await Promise.all([o.data(),a.data()]),u=c[0],h=c[1],{selectedIndices:d,selectedScores:p}=gm(u,h,t,s,r,i);return o!==n&&o.dispose(),a!==e&&a.dispose(),{selectedIndices:Zs(d,"int32"),selectedScores:Zs(p)}}const bD=vD;/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yD(n,e,t,s=.5,r=Number.NEGATIVE_INFINITY,i=!1){const o=G(n,"boxes","nonMaxSuppression"),a=G(e,"scores","nonMaxSuppression"),l=Xu(o,a,t,s,r,null),c=l.maxOutputSize,u=l.iouThreshold,h=l.scoreThreshold,d={boxes:o,scores:a},p={maxOutputSize:c,iouThreshold:u,scoreThreshold:h,padToMaxOutputSize:i},f=ee.runKernel(g2,d,p);return{selectedIndices:f[0],validOutputs:f[1]}}const wD=ie({nonMaxSuppressionPadded_:yD});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function SD(n,e,t,s=.5,r=Number.NEGATIVE_INFINITY,i=!1){const o=G(n,"boxes","nonMaxSuppressionAsync"),a=G(e,"scores","nonMaxSuppressionAsync"),l=Xu(o,a,t,s,r,null),c=l.maxOutputSize,u=l.iouThreshold,h=l.scoreThreshold,[d,p]=await Promise.all([o.data(),a.data()]),{selectedIndices:f,validOutputs:x}=av(d,p,c,u,h,i);return o!==n&&o.dispose(),a!==e&&a.dispose(),{selectedIndices:Zs(f,"int32"),validOutputs:Ht(x,"int32")}}const CD=SD;/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _D(n,e,t=!1,s=!1){const r=G(n,"images","resizeBilinear");N(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),N(e.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${e}.`),N(s===!1||t===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let i=r,o=!1;r.rank===3&&(o=!0,i=se(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const a={images:i},l={alignCorners:t,halfPixelCenters:s,size:e},c=ee.runKernel(Gd,a,l);return o?se(c,[c.shape[1],c.shape[2],c.shape[3]]):c}const u4=ie({resizeBilinear_:_D});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function TD(n,e,t=!1,s=!1){const r=G(n,"images","resizeNearestNeighbor");N(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),N(e.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${e}.`),N(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),N(s===!1||t===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let i=r,o=!1;r.rank===3&&(o=!0,i=se(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const a={images:i},l={alignCorners:t,halfPixelCenters:s,size:e},c=ee.runKernel(Wd,a,l);return o?se(c,[c.shape[1],c.shape[2],c.shape[3]]):c}const h4=ie({resizeNearestNeighbor_:TD});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ID(n,e="binary",t=!1,s=.5){const r=G(n,"image","threshold"),i=.2989,o=.587,a=.114,l=r.shape[0]*r.shape[1];let c=Z(Zs([s]),255),u,h,d,p;if(N(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),N(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),N(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),N(e==="otsu"||e==="binary",()=>`Method must be binary or otsu, but was ${e}`),r.shape[2]===3){[u,h,d]=kr(r,[1,1,1],-1);const m=Z(u,i),g=Z(h,o),v=Z(d,a);p=ke(ke(m,g),v)}else p=n;if(e==="otsu"){const m=EN(qe(QC(p),"int32"),EC([]),256);c=ED(m,l)}const f=t?qu(p,c):Dr(p,c);return qe(Z(f,255),"int32")}function ED(n,e){let t=Zs([-1]),s=Zs([0]),r=Zs([0]),i,o,a,l,c,u;for(let h=0;h`Error in transform: image must be rank 4,but got rank ${o.rank}.`),N(a.rank===2&&(a.shape[0]===o.shape[0]||a.shape[0]===1)&&a.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),N(i==null||i.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${i}.`);const l={image:o,transforms:a},c={interpolation:t,fillMode:s,fillValue:r,outputShape:i};return ee.runKernel(nm,l,c)}const RD=ie({transform_:AD});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function MD(n,e,t){const s=G(n,"a","bandPart");N(s.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`);const r=s.shape,[i,o]=s.shape.slice(-2);let a,l;typeof e=="number"?(N(e%1===0,()=>`bandPart(): numLower must be an integer, got ${e}.`),N(e<=i,()=>`bandPart(): numLower (${e}) must not be greater than the number of rows (${i}).`),a=G(e<0?i:e,"numLower","bandPart")):(N(e.dtype==="int32",()=>"bandPart(): numLower's dtype must be an int32."),a=zs(Lf(e,0),i,Bh(e,i))),typeof t=="number"?(N(t%1===0,()=>`bandPart(): numUpper must be an integer, got ${t}.`),N(t<=o,()=>`bandPart(): numUpper (${t}) must not be greater than the number of columns (${o}).`),l=G(t<0?o:t,"numUpper","bandPart")):(N(t.dtype==="int32",()=>"bandPart(): numUpper's dtype must be an int32."),l=zs(Lf(t,0),o,Bh(t,o)));const c=se(Uh(0,i,1,"int32"),[-1,1]),u=Uh(0,o,1,"int32"),h=ft(c,u),d=Ao(qu(h,a),Ml(h,Bn(l))),p=On([i,o],s.dtype);return se(Ji(bl(se(s,[-1,i,o])).map(f=>zs(d,f,p))),r)}const ND=ie({bandPart_:MD});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $D(n){let e;if(Array.isArray(n)){e=!1,N(n!=null&&n.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const r=n[0].shape[0];for(let i=1;i`Gram-Schmidt: Non-unique lengths found in the input vectors: (${n[i].shape[0]} vs. ${r})`)}else e=!0,n=kr(n,n.shape[0],0).map(r=>sp(r,[0]));N(n.length<=n[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${n.length}) exceeds number of dimensions (${n[0].shape[0]}).`);const t=[],s=n;for(let r=0;r{let i=s[r];if(r>0)for(let o=0;o=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${n.rank}`),n.rank===2)return ay(n,e);{const t=n.shape.slice(0,n.shape.length-2).reduce((l,c)=>l*c),s=bl(se(n,[t,n.shape[n.shape.length-2],n.shape[n.shape.length-1]]),0),r=[],i=[];s.forEach(l=>{const[c,u]=ay(l,e);r.push(c),i.push(u)});const o=se(Ji(r,0),n.shape),a=se(Ji(i,0),n.shape);return[o,a]}}function ay(n,e=!1){return ee.tidy(()=>{N(n.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${n.shape.length}D Tensor.`);const t=n.shape[0],s=n.shape[1];let r=HC(t),i=il(n);const o=Rg([[1]],[1,1]);let a=il(o);const l=t>=s?s:t;for(let c=0;c{const p=fn(i,[c,c],[t-c,1]),f=dm(p),x=fn(i,[c,c],[1,1]),m=zs(Dr(x,0),Rg([[-1]]),Rg([[1]])),g=ft(x,Z(m,f)),v=ut(p,g);v.shape[0]===1?a=il(o):a=tr([o,fn(v,[1,0],[v.shape[0]-1,v.shape[1]])],0);const b=Bn(ut(Jt(m,g),f)),y=fn(i,[c,0],[t-c,s]),w=Z(b,a),C=qt(a);if(c===0)i=ft(y,Jt(w,Jt(C,y)));else{const R=ft(y,Jt(w,Jt(C,y)));i=tr([fn(i,[0,0],[c,s]),R],0)}const T=qt(w),E=fn(r,[0,c],[t,r.shape[1]-c]);if(c===0)r=ft(E,Jt(Jt(E,a),T));else{const R=ft(E,Jt(Jt(E,a),T));r=tr([fn(r,[0,0],[t,c]),R],1)}return[a,i,r]}),Nt([u,h,d])}return!e&&t>s&&(r=fn(r,[0,0],[t,s]),i=fn(i,[0,0],[s,s])),[r,i]})}const LD=ie({qr_:PD});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const So={flipLeftRight:Q$,grayscaleToRGB:tD,resizeNearestNeighbor:h4,resizeBilinear:u4,rgbToGrayscale:sD,rotateWithOffset:iD,cropAndResize:Z$,nonMaxSuppression:aD,nonMaxSuppressionAsync:mD,nonMaxSuppressionWithScore:xD,nonMaxSuppressionWithScoreAsync:bD,nonMaxSuppressionPadded:wD,nonMaxSuppressionPaddedAsync:CD,threshold:kD,transform:RD},FD={bandPart:ND,gramSchmidt:DD,qr:LD};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const OD=new Map,zD=new Map;class Ku{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Hr{constructor(){this.classNameMap={}}static getMap(){return Hr.instance==null&&(Hr.instance=new Hr),Hr.instance}static register(e){Hr.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function we(n,e,t){N(n.className!=null,()=>"Class being registered does not have the static className property defined."),N(typeof n.className=="string",()=>"className is required to be a string, but got type "+typeof n.className),N(n.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),typeof e>"u"&&(e="Custom"),typeof t>"u"&&(t=n.className);const s=t,r=e+">"+s;return Hr.register(n),OD.set(r,n),zD.set(n,r),n}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ta extends Ku{minimize(e,t=!1,s){const{value:r,grads:i}=this.computeGradients(e,s);if(s!=null){const o=s.map(a=>({name:a.name,tensor:i[a.name]}));this.applyGradients(o)}else this.applyGradients(i);return Nt(i),t?r:(r.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return K5(e,t)}dispose(){this.iterations_!=null&&Nt(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ht(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(Ta,Symbol.hasInstance,{value:n=>n.minimize!=null&&n.computeGradients!=null&&n.applyGradients!=null});/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class d4 extends Ta{static get className(){return"Adadelta"}constructor(e,t,s=null){super(),this.learningRate=e,this.rho=t,this.epsilon=s,this.accumulatedGrads=[],this.accumulatedUpdates=[],s==null&&(this.epsilon=ee.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(s=>s.name):Object.keys(e)).forEach((s,r)=>{const i=ee.registeredVariables[s],o=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${s}/accum_grad`,variable:le(()=>Xt(i).variable(o))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${s}/accum_var`,variable:le(()=>Xt(i).variable(o))});const a=Array.isArray(e)?e[r].tensor:e[s];if(a==null)return;const l=this.accumulatedGrads[r].variable,c=this.accumulatedUpdates[r].variable;le(()=>{const u=ke(Z(l,this.rho),Z(yn(a),1-this.rho)),h=Z(ut(As(ke(c,this.epsilon)),As(ke(l,this.epsilon))),a),d=ke(Z(c,this.rho),Z(yn(h),1-this.rho));l.assign(u),c.assign(d);const p=ke(Z(h,-this.learningRate),i);i.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Nt(this.accumulatedGrads.map(e=>e.variable)),Nt(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=e.length/2,s=!1;this.accumulatedGrads=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(s)})),this.accumulatedUpdates=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(s)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class p4 extends Ta{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(s=>s.name):Object.keys(e)).forEach((s,r)=>{const i=ee.registeredVariables[s];this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${s}/accumulator`,variable:le(()=>um(i.shape,this.initialAccumulatorValue).variable(!1))});const o=Array.isArray(e)?e[r].tensor:e[s];if(o==null)return;const a=this.accumulatedGrads[r].variable;le(()=>{const l=ke(a,yn(o));a.assign(l);const c=ke(Z(ut(o,As(ke(l,ee.backend.epsilon()))),-this.learningRate),i);i.assign(c)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Nt(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);const t=!1;this.accumulatedGrads=e.map(s=>({originalName:s.name,variable:s.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class f4 extends Ta{static get className(){return"Adam"}constructor(e,t,s,r=null){super(),this.learningRate=e,this.beta1=t,this.beta2=s,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],le(()=>{this.accBeta1=Ht(t).variable(),this.accBeta2=Ht(s).variable()}),r==null&&(this.epsilon=ee.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);le(()=>{const s=ft(1,this.accBeta1),r=ft(1,this.accBeta2);t.forEach((i,o)=>{const a=ee.registeredVariables[i],l=!1;this.accumulatedFirstMoment[o]==null&&(this.accumulatedFirstMoment[o]={originalName:`${i}/m`,variable:le(()=>Xt(a).variable(l))}),this.accumulatedSecondMoment[o]==null&&(this.accumulatedSecondMoment[o]={originalName:`${i}/v`,variable:le(()=>Xt(a).variable(l))});const c=Array.isArray(e)?e[o].tensor:e[i];if(c==null)return;const u=this.accumulatedFirstMoment[o].variable,h=this.accumulatedSecondMoment[o].variable,d=ke(Z(u,this.beta1),Z(c,1-this.beta1)),p=ke(Z(h,this.beta2),Z(yn(c),1-this.beta2)),f=ut(d,s),x=ut(p,r);u.assign(d),h.assign(p);const m=ke(Z(ut(f,ke(As(x),this.epsilon)),-this.learningRate),a);a.assign(m)}),this.accBeta1.assign(Z(this.accBeta1,this.beta1)),this.accBeta2.assign(Z(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Nt(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Nt(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e),le(()=>{this.accBeta1.assign(xl(this.beta1,this.iterations_+1)),this.accBeta2.assign(xl(this.beta2,this.iterations_+1))});const t=e.length/2,s=!1;this.accumulatedFirstMoment=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(s)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(s)}))}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)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class m4 extends Ta{static get className(){return"Adamax"}constructor(e,t,s,r=null,i=0){super(),this.learningRate=e,this.beta1=t,this.beta2=s,this.epsilon=r,this.decay=i,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],le(()=>{this.iteration=Ht(0).variable(),this.accBeta1=Ht(t).variable()}),r==null&&(this.epsilon=ee.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);le(()=>{const s=ft(1,this.accBeta1),r=ut(-this.learningRate,ke(Z(this.iteration,this.decay),1));t.forEach((i,o)=>{const a=ee.registeredVariables[i],l=!1;this.accumulatedFirstMoment[o]==null&&(this.accumulatedFirstMoment[o]={originalName:`${i}/m`,variable:Xt(a).variable(l)}),this.accumulatedWeightedInfNorm[o]==null&&(this.accumulatedWeightedInfNorm[o]={originalName:`${i}/v`,variable:Xt(a).variable(l)});const c=Array.isArray(e)?e[o].tensor:e[i];if(c==null)return;const u=this.accumulatedFirstMoment[o].variable,h=this.accumulatedWeightedInfNorm[o].variable,d=ke(Z(u,this.beta1),Z(c,1-this.beta1)),p=Z(h,this.beta2),f=Ls(c),x=Ca(p,f);u.assign(d),h.assign(x);const m=ke(Z(ut(r,s),ut(d,ke(x,this.epsilon))),a);a.assign(m)}),this.iteration.assign(ke(this.iteration,1)),this.accBeta1.assign(Z(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Nt(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Nt(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)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class cv extends Ta{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(s=>s.name):Object.keys(e)).forEach((s,r)=>{const i=Array.isArray(e)?e[r].tensor:e[s];if(i==null)return;const o=ee.registeredVariables[s];le(()=>{const a=ke(Z(this.c,i),o);o.assign(a)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=er(Ht(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(e=await this.extractIterations(e),e.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class g4 extends cv{static get className(){return"Momentum"}constructor(e,t,s=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=s,this.accumulations=[],this.m=Ht(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(s=>s.name):Object.keys(e)).forEach((s,r)=>{const i=ee.registeredVariables[s];this.accumulations[r]==null&&(this.accumulations[r]={originalName:`${s}/momentum`,variable:le(()=>Xt(i).variable(!1))});const o=this.accumulations[r].variable,a=Array.isArray(e)?e[r].tensor:e[s];a!=null&&le(()=>{let l;const c=ke(Z(this.m,o),a);this.useNesterov?l=ke(Z(this.c,ke(a,Z(c,this.m))),i):l=ke(Z(this.c,c),i),o.assign(c),i.assign(l)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Nt(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);const t=!1;this.accumulations=e.map(s=>({originalName:s.name,variable:s.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class x4 extends Ta{static get className(){return"RMSProp"}constructor(e,t=.9,s=0,r=null,i=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=s,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=i,r==null&&(this.epsilon=ee.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(s=>s.name):Object.keys(e)).forEach((s,r)=>{const i=ee.registeredVariables[s],o=!1;this.accumulatedMeanSquares[r]==null&&(this.accumulatedMeanSquares[r]={originalName:`${s}/rms`,variable:le(()=>Xt(i).variable(o))}),this.accumulatedMoments[r]==null&&(this.accumulatedMoments[r]={originalName:`${s}/momentum`,variable:le(()=>Xt(i).variable(o))}),this.accumulatedMeanGrads[r]==null&&this.centered&&(this.accumulatedMeanGrads[r]={originalName:`${s}/mg`,variable:le(()=>Xt(i).variable(o))});const a=Array.isArray(e)?e[r].tensor:e[s];if(a==null)return;const l=this.accumulatedMeanSquares[r].variable,c=this.accumulatedMoments[r].variable;le(()=>{const u=ke(Z(l,this.decay),Z(yn(a),1-this.decay));if(this.centered){const h=this.accumulatedMeanGrads[r].variable,d=ke(Z(h,this.decay),Z(a,1-this.decay)),p=ut(Z(a,this.learningRate),As(ft(u,ke(yn(d),this.epsilon)))),f=ke(Z(c,this.momentum),p);l.assign(u),h.assign(d),c.assign(f);const x=ft(i,f);i.assign(x)}else{const h=ke(Z(l,this.decay),Z(yn(a),1-this.decay)),d=ke(Z(c,this.momentum),ut(Z(a,this.learningRate),As(ke(h,this.epsilon))));l.assign(h),c.assign(d);const p=ft(i,d);i.assign(p)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Nt(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Nt(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Nt(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(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,s=!1;this.accumulatedMeanSquares=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(s)})),this.accumulatedMoments=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(s)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(r=>({originalName:r.name,variable:r.tensor.variable(s)})))}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)}}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const BD=[d4,p4,f4,m4,g4,x4,cv];function UD(){for(const n of BD)we(n)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const VD="model",WD=".json",GD=".weights.bin";function ly(n){return new Promise(e=>setTimeout(e)).then(n)}class yl{constructor(e){if(!oe().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(yl.URL_SCHEME)&&(e=e.slice(yl.URL_SCHEME.length)),(e==null||e.length===0)&&(e=VD),this.modelJsonFileName=e+WD,this.weightDataFileName=e+GD}async save(e){if(typeof document>"u")throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=wa.join(e.weightData),s=window.URL.createObjectURL(new Blob([t],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const r=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],i=kC(e,r),o=window.URL.createObjectURL(new Blob([JSON.stringify(i)],{type:"application/json"})),a=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=o,await ly(()=>a.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){const l=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;l.download=this.weightDataFileName,l.href=s,await ly(()=>l.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:lm(e)}}}}yl.URL_SCHEME="downloads://";const HD=n=>oe().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(yl.URL_SCHEME)?qD(n.slice(yl.URL_SCHEME.length)):null;ls.registerSaveRouter(HD);function qD(n="model"){return new yl(n)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cy(n,e,t,s){o(n),t=t??0,s=s??1,a(t,s);let r=0;const i=l=>(l.then(c=>{const u=t+ ++r/n.length*(s-t);return e(u),c}),l);function o(l){N(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function a(l,c){N(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),N(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${c}`),N(c>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${c}`)}return Promise.all(n.map(i))}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function XD(n,e){e==null&&(e={});const t=e.fetchFunc==null?oe().platform.fetch:e.fetchFunc,s=n.map(h=>t(h,e.requestInit,{isBinary:!0})),a=(e.onProgress==null?await Promise.all(s):await cy(s,e.onProgress,0,.5)).map(h=>h.arrayBuffer());return e.onProgress==null?await Promise.all(a):await cy(a,e.onProgress,.5,1)}function KD(n,e){var t;const s=e.fetchFunc==null?oe().platform.fetch:e.fetchFunc;let r=0,i;return(t=e.onProgress)===null||t===void 0||t.call(e,0),new ReadableStream({pull:async o=>{for(var a;r"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=oe().platform.fetch,N(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&N(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{},this.loadOptions=t}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const s=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r=kC(e,s);if(t.body.append("model.json",new Blob([JSON.stringify(r)],{type:YD}),"model.json"),e.weightData!=null){const o=wa.join(e.weightData);t.body.append("model.weights.bin",new Blob([o],{type:jD}),"model.weights.bin")}const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:lm(e),responses:[i]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${i.status}.`)}async loadModelJSON(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch{let o=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?o+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":o+=" Please make sure the server is serving valid JSON for this request.",new Error(o)}const s=t.modelTopology,r=t.weightsManifest;if(s==null&&r==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return t}async load(){if(this.loadOptions.streamWeights)return this.loadStream();const e=await this.loadModelJSON();return fM(e,t=>this.loadWeights(t))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),s=ny(e.weightsManifest),r=()=>KD(t,this.loadOptions);return Object.assign(Object.assign({},e),{weightSpecs:s,getWeightStream:r})}async getWeightUrls(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[s,r]=ZD(t),i=this.weightPathPrefix||s,o=[],a=[];for(const l of e)for(const c of l.paths)this.weightUrlConverter!=null?a.push(this.weightUrlConverter(c)):o.push(i+c+r);return this.weightUrlConverter&&o.push(...await Promise.all(a)),o}async loadWeights(e){const t=await this.getWeightUrls(e),s=ny(e),r=await XD(t,this.loadOptions);return[s,r]}}uv.URL_SCHEME_REGEX=/^https?:\/\//;function ZD(n){const e=n.lastIndexOf("/"),t=n.lastIndexOf("?"),s=n.substring(0,e),r=t>e?n.substring(t):"";return[s+"/",r]}function uy(n){return n.match(uv.URL_SCHEME_REGEX)!=null}const v4=(n,e)=>{if(typeof fetch>"u"&&(e==null||e.fetchFunc==null))return null;{let t=!0;if(Array.isArray(n)?t=n.every(s=>uy(s)):t=uy(n),t)return JD(n,e)}return null};ls.registerSaveRouter(v4);ls.registerLoadRouter(v4);function JD(n,e){return new uv(n,e)}function xm(n,e){const t=n.shape.length,s=e.shape.length;if(t<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${t}.`);if(s<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${s}.`);if(e.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.shape[s-1]>t)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${e.shape[s-1]} vs. ${t}`);if(re(n.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${n.shape}.`);const r=e.shape,i=r[r.length-1];let o=1;for(let h=0;hh/c),1].slice(0,i);return[l,o,c,u]}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cx=-2,QD=-1;function hv(n,e,t){const s=n.shape.length;N(s===e.length,()=>`Error in slice${s}D: Length of begin ${e} must match the rank of the array (${s}).`),N(s===t.length,()=>`Error in slice${s}D: Length of size ${t} must match the rank of the array (${s}).`);for(let r=0;r`Error in slice${s}D: begin[${r}] + size[${r}] (${e[r]+t[r]}) would overflow input.shape[${r}] (${n.shape[r]})`)}function dv(n,e,t){const s=[];for(let r=0;r1){s=r;break}for(let r=s+1;r0||t[r]!==n[r])return!1;return!0}function y4(n,e){let t=n.length>0?n[n.length-1]:1;for(let s=0;s{N(o!==-1,()=>"slice() does not support negative begin indexing.")});let i;return t==null?i=new Array(r).fill(-1):typeof t=="number"?i=[t,...new Array(r-1).fill(-1)]:t.lengtho>=0?o:(N(o===-1,()=>`Negative size values should be exactly -1 but got ${o} for the slice() size at index ${a}.`),n.shape[a]-s[a])),[s,i]}function pv(n,e,t,s,r,i,o,a,l){let c;if(s==null?(c=new Array(e.length),c.fill(1)):c=s,o!=null&&o&o-1)throw new Error("Multiple ellipses in slice is not allowed.");let u=!1;const h={dims:c.length,numAddAxisAfterEllipsis:0,begin:e.slice(),end:t.slice(),strides:c.slice(),beginMask:r,endMask:i,ellipsisMask:o,newAxisMask:a,shrinkAxisMask:l};for(let b=0;b0?0:-1,d.strides[b]>0?w:w-1];if(y&&d.strides[b]<=0)throw Error("only stride 1 allowed on non-range indexing.");x=x&&d.strides[b]===1;const E=!!(d.beginMask&1<=w)throw Error(`slice index ${d.begin[b]} of dimension ${b} out of bounds.`)}else d.begin[b]=hy(d.begin[b],0,d.strides[b],w,C,T),d.end[b]=hy(d.end[b],1,d.strides[b],w,C,T);const k=d.strides[b]===1&&d.begin[b]===0&&d.end[b]===w;p=p&&k,f=f&&(b===0&&d.strides[b]===1||k)}else p=p&&d.strides[b]===1&&E,f=f&&(b===0&&d.strides[b]===1||E);let R,_=!1;if(d.beginValid&&d.endValid?(R=d.end[b]-d.begin[b],_=!0):y?(R=1,_=!0):E&&w>=0&&(d.strides[b]<0?R=-w:R=w,_=!0),_){let k;R===0||R<0!=d.strides[b]<0?k=0:k=Math.trunc(R/d.strides[b])+(R%d.strides[b]!==0?1:0),m.push(k)}else m.push(-1)}for(let b=0;b=0?g.push(m[y]):y===cx&&g.push(1)}return{finalShapeSparse:g.filter((b,y)=>d.finalShapeGatherIndices[y]!==cx),finalShape:g,isIdentity:p,sliceDim0:f,isSimpleSlice:x,begin:d.begin,end:d.end,strides:d.strides}}function e7(n,e){e.beginMask=0,e.endMask=0,e.shrinkAxisMask=0;let t=0;e.beginValid=n.begin!=null,e.endValid=n.end!=null,e.begin=new Array(e.dims),e.end=new Array(e.dims),e.strides=new Array(e.dims),e.finalShapeGatherIndices=[],e.finalShapeGatherIndicesSparse=[],e.inputShapeGatherIndicesSparse=new Array(e.dims);for(let s=0;s0?i[e]:i[e+1&1];{const o=n<0?s+n:n;return oi[1]?i[1]:o}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class t7{static sgd(e){return new cv(e)}static momentum(e,t,s=!1){return new g4(e,t,s)}static rmsprop(e,t=.9,s=0,r=null,i=!1){return new x4(e,t,s,r,i)}static adam(e=.001,t=.9,s=.999,r=null){return new f4(e,t,s,r)}static adadelta(e=.001,t=.95,s=null){return new d4(e,t,s)}static adamax(e=.002,t=.9,s=.999,r=null,i=0){return new m4(e,t,s,r,i)}static adagrad(e,t=.1){return new p4(e,t)}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Wa=t7;/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const n7=typeof requestAnimationFrame<"u"?requestAnimationFrame:typeof setImmediate<"u"?setImmediate:n=>n();function w4(){return new Promise(n=>n7(()=>n()))}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bm(n,e){const t=n[0].length;n.forEach((r,i)=>{N(r.length===t,()=>`Error in concat${t}D: rank of tensors[${i}] must be the same as the rank of the rest (${t})`)}),N(e>=0&&e`Error in concat${t}D: axis must be between 0 and ${t-1}.`);const s=n[0];n.forEach((r,i)=>{for(let o=0;o`Error in concat${t}D: Shape of tensors[${i}] (${r}) does not match the shape of the rest (${s}) along the non-concatenated axis ${i}.`)})}function nr(n,e){const t=n[0].slice();for(let s=1;s=0)if(a>=0){if(a!==i)throw new Error(`rt input.shape and shape=${e} are incompatible: rt input.shape[${r+n}] = ${i} but shape[${r+n}] = ${a}`)}else s[o]=i}return s}function C4(n){const e={FIRST_DIM_SIZE:di.FIRST_DIM_SIZE,VALUE_ROWIDS:di.VALUE_ROWIDS,ROW_LENGTHS:di.ROW_LENGTHS,ROW_SPLITS:di.ROW_SPLITS,ROW_LIMITS:di.ROW_LIMITS,ROW_STARTS:di.ROW_STARTS},t=[];for(const s of n)if(s in e)t.push(e[s]);else break;return t}function _4(n){return n.length===0?0:n[0]===di.FIRST_DIM_SIZE?n.length-1:n.length}function T4(n,e){if(n==null||e==null)return;const t=n.length,s=e.length;if(t>=s)throw new Error(`defaultValue.shape=${n} and ragged tensor flatValues.shape=${e}, are incompatible: defaultValue.rank = ${t} must be less than ragged tensor input flatValues.rank = ${s})`);for(let r=0;r=0&&o>=0&&i!==1&&i!==o)throw new Error(`defaultValue.shape=${n}, and ragged tensor input flatValues.shape=${e} are incompatible: defaultValue.shape[${r-n.length}] = ${i} but ragged tensor input.flatValues.shape[${r-n.length}] = ${o}`)}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fv=30;function ym(n){return n<=fv?n:X1(n,Math.floor(Math.sqrt(n)))}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wm(n,e,t){const s=t*(typeof n=="number"?n:n[0]),r=e*(typeof n=="number"?n:n[1]);return[s,r]}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Dl(n,e,t,s=!0){let r=[];if(s)r=r.concat(e.slice(0)),r.push(n[0]/t),r=r.concat(n.slice(1));else{r=r.concat(n[0]);const i=e.length;for(let o=0;o=e*2+1||o%2===1?i.push(o):r.push(o);s.push(...r),s.push(0),s.push(...i)}return s}function Ll(n,e,t,s=!0){const r=[];s?r.push(n[0]/t):r.push(n[0]*t);for(let i=1;i/g,dy=",",py="...";function Rm(n,e){n=n.replace(/\s/g,"");const t=(n.length-n.replace(s7,"").length)/Mg.length;if(t<1)throw new Error("Equations without an arrow are not supported.");if(t>1)throw new Error(`Equation must contain exactly one arrow ("${Mg}").`);const[s,r]=n.split(Mg);N(s.indexOf(py)===-1,()=>`The ellipsis notation ("${py}") is not supported yet.`);const i=s.split(dy),o=i.length;if(e!==o)throw new Error(`Expected ${o} input tensors, received ${e}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const a=[];for(let d=0;df.indexOf(p)!==-1))throw new Error(`Output subscripts contain the label ${p} not present in the input subscripts.`);a.indexOf(p)===-1&&a.push(p)}for(let d=0;dr!==-1),{permutationIndices:t,expandDims:s}}function Nm(n,e,t){const s=new Array(n);for(let r=0;r`Expected dimension ${s[e[r][o]]} at axis ${o} of input shaped ${JSON.stringify(i)}, but got dimension ${i[o]}`)}}function $m(n,e){const t=n,s=[];let r=0;n.length===0&&t.push(-1),r=n.length+1;for(let o=0;oe===t)}function r7(n,e){const t=[];for(let s=0;s"Number of splits must evenly divide the axis."),s=new Array(e).fill(n.shape[t]/e);else{const r=e.reduce((o,a)=>(a===-1&&(o+=1),o),0);N(r<=1,()=>"There should be only one negative value in split array.");const i=e.indexOf(-1);if(i!==-1){const o=e.reduce((a,l)=>l>0?a+l:a);e[i]=n.shape[t]-o}N(n.shape[t]===e.reduce((o,a)=>o+a),()=>"The sum of sizes must match the size of the axis dimension."),s=e}return s}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function N4(n){return`Received SparseTensor with denseShape[0] = 0 but + indices.shape[0] = ${n}`}function $4(n,e){return`indices(${n}, 0) is invalid: ${e} < 0`}function D4(n,e,t){return`indices(${n}, 0) is invalid: ${e} >= ${t}`}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function P4(n,e){return`only one output dimension may be -1, not both ${n} and ${e}`}function L4(n,e){return`size ${n} must be non-negative, not ${e}`}function F4(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function O4(n,e){const t=re(n),s=re(e);return`Input to reshape is a SparseTensor with ${t} + dense values, but the requested shape requires a multiple of ${s}. inputShape=${n} outputShape= ${e}`}function z4(n,e){const t=re(n),s=re(e);return`Input to reshape is a tensor with ${t} dense values, but the requested shape has ${s}. inputShape=${n} outputShape=${e}`}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ux(){return"segment ids must be >= 0"}function B4(){return"segment ids are not increasing"}function U4(n,e){return`Segment id ${n} out of range [0, ${e}), possibly because segmentIds input is not sorted.`}function V4(n,e,t){return`Bad: indices[${n}] == ${e} out of range [0, ${t})`}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function i7(n,e){let t=!1,s;for(n<=fv?(s=n,t=!0):s=X1(n,Math.floor(Math.sqrt(n)));!t;)s>e||s===n?t=!0:s=X1(n,s+1);return s}function W4(n,e,t){const s=[],r=n.length;for(let i=0;ir))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${s}`);if(s<0&&(s+=r),s>i)throw new Error(`batchDims (${s}) must be less than rank(x) ( + ${i}).`);if(tCi(e))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function G4(n){return n.map(e=>_o(e))}const o7=Object.freeze(Object.defineProperty({__proto__:null,ERF_A1:Tm,ERF_A2:Im,ERF_A3:Em,ERF_A4:km,ERF_A5:Am,ERF_P:_m,PARALLELIZE_THRESHOLD:fv,get RowPartitionType(){return di},SELU_SCALE:op,SELU_SCALEALPHA:ip,applyActivation:iv,assertAndGetBroadcastShape:pt,assertAxesAreInnerMostDims:Kn,assertParamsConsistent:bm,assignToTypedArray:A4,axesAreInnerMostDims:F2,calculateShapes:so,checkEinsumDimSizes:Nm,checkPadOnDimRoundingMode:or,combineLocations:WC,combineRaggedTensorToTensorShapes:S4,complexWithEvenIndex:E4,complexWithOddIndex:k4,computeConv2DInfo:Cn,computeConv3DInfo:Ri,computeDefaultPad:M2,computeDilation2DInfo:Sa,computeOptimalWindowSize:ym,computeOutAndReduceShapes:Wn,computeOutShape:nr,computePool2DInfo:Rs,computePool3DInfo:$r,convertConv2DDataFormat:wr,decodeEinsumEquation:Rm,eitherStridesOrDilationsAreOne:gs,expandShapeToKeepDim:Vn,exponent:M4,exponents:R4,fromStringArrayToUint8:G4,fromUint8ToStringArray:Ti,getAxesPermutation:ln,getBroadcastDims:oa,getComplexWithIndex:mv,getEinsumComputePath:$m,getEinsumPermutation:Mm,getFusedBiasGradient:rv,getFusedDyActivation:sv,getImageCenter:wm,getInnerMostAxes:xn,getPermuted:Pl,getRaggedRank:_4,getReductionAxes:rs,getReshaped:Dl,getReshapedPermuted:Ll,getRowPartitionTypesHelper:C4,getSliceBeginCoords:Sm,getSliceSize:Cm,getSparseFillEmptyRowsIndicesDenseShapeMismatch:N4,getSparseFillEmptyRowsNegativeIndexErrorMessage:$4,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:D4,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:F4,getSparseReshapeInputOutputMismatchErrorMessage:z4,getSparseReshapeInputOutputMultipleErrorMessage:O4,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:P4,getSparseReshapeNegativeOutputDimErrorMessage:L4,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:V4,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:ux,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:B4,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:U4,getUndoAxesPermutation:no,isIdentityPermutation:Dm,mergeRealAndImagArrays:_i,prepareAndValidate:xm,prepareSplitSize:Pm,shouldFuse:ov,splitRealAndImagArrays:I4,stridesOrDilationsArePositive:ml,tupleValuesAreOne:fl,upcastType:ds,validateDefaultValueShape:T4,warn:Ir},Symbol.toStringTag,{value:"Module"}));/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */UD();/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const H4={kernelName:td,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Z(n,rp(qe(t,"float32"),-1))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const a7={kernelName:Yc,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>{const s=yn(qe(t,"float32")),r=As(ft(Ht(1),s));return Bn(ut(n,r))}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const l7={kernelName:Zc,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>{const s=As(ft(yn(qe(t,"float32")),1));return ut(n,s)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const c7={kernelName:El,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=pt(t.shape,s.shape);return{a:()=>{let a=n;const l=rs(t.shape,r);return l.length>0&&(a=lt(a,l)),se(a,t.shape)},b:()=>{let a=n;const l=rs(s.shape,r);return l.length>0&&(a=lt(a,l)),se(a,s.shape)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const u7={kernelName:w0,saveAllInputs:!0,gradFunc:(n,e)=>{const t={};return e.forEach((s,r)=>{t[r]=()=>n.clone()}),t}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const h7={kernelName:nd,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Xt(t)}}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const d7={kernelName:sd,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Xt(t)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const p7={kernelName:Jc,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ut(n,As(ft(Ht(1),yn(qe(t,"float32")))))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const f7={kernelName:Qc,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>{const s=As(ke(Ht(1),yn(qe(t,"float32"))));return ut(n,s)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const m7={kernelName:nu,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=pt(t.shape,s.shape);return{a:()=>{const a=ke(yn(t),yn(s));let l=Z(n,ut(s,a));const c=rs(t.shape,r);return c.length>0&&(l=lt(l,c)),se(l,t.shape)},b:()=>{const a=ke(yn(t),yn(s));let l=Bn(Z(n,ut(t,a)));const c=rs(s.shape,r);return c.length>0&&(l=lt(l,c)),se(l,s.shape)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const g7={kernelName:eu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ut(n,ke(yn(qe(t,"float32")),1))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const x7={kernelName:tu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ut(n,ft(Ht(1),yn(qe(t,"float32"))))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function v7(n,e,t,s,r,i){const o=G(n,"dy","avgPool3dGrad"),a=G(e,"input","avgPool3dGrad");let l=o,c=a,u=!1;a.rank===4&&(u=!0,l=se(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),c=se(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),N(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),N(c.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${c.rank}.`),or("avgPool3dGrad",r,i);const h={dy:l,input:c},d={filterSize:t,strides:s,pad:r,dimRoundingMode:i},p=ee.runKernel(T0,h,d);return u?se(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}const b7=ie({avgPool3dGrad_:v7});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const y7={kernelName:id,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{filterSize:r,strides:i,pad:o,dimRoundingMode:a}=t;return{x:()=>b7(n,s,r,i,o,a)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function w7(n,e,t,s,r){const i=G(n,"dy","avgPoolGrad"),o=G(e,"input","avgPoolGrad");N(o.rank===i.rank,()=>`Rank of input (${o.rank}) does not match rank of dy (${i.rank})`);let a=o,l=i,c=!1;o.rank===3&&(c=!0,a=se(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=se(i,[1,i.shape[0],i.shape[1],i.shape[2]])),N(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),N(a.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${a.rank}.`);const u={dy:l,input:a},h={filterSize:t,strides:s,pad:r},d=ee.runKernel(_0,u,h);return c?se(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const S7=ie({avgPoolGrad_:w7});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const C7={kernelName:rd,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{filterSize:r,strides:i,pad:o}=t;return{x:()=>S7(n,s,r,i,o)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _7={kernelName:od,inputsToSave:["a","b"],gradFunc:(n,e,t)=>{const[s,r]=e,{transposeA:i,transposeB:o}=t;return!i&&!o?{a:()=>Jt(n,r,!1,!0),b:()=>Jt(s,n,!0,!1)}:!i&&o?{a:()=>Jt(n,r,!1,!1),b:()=>Jt(n,s,!0,!1)}:i&&!o?{a:()=>Jt(r,n,!1,!0),b:()=>Jt(s,n,!1,!1)}:{a:()=>Jt(r,n,!0,!0),b:()=>Jt(n,s,!0,!0)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const T7={kernelName:ad,gradFunc:(n,e,t)=>{const{blockShape:s,crops:r}=t;return{x:()=>H2(n,s,r)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const I7={kernelName:NR,gradFunc:(n,e,t)=>{const s=t,r=s.inputShape,i=s.shape,o=Array.from(i);for(let l=r.length-1;l>=0;l--)if(r[l]===i[l])o[l]=1;else if(r[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${i}].`);const a=[];for(let l=0;l1&&a.push(l);return{x:()=>lt(n,a,!0)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const E7={kernelName:su,gradFunc:n=>({x:()=>n.clone()})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const k7={kernelName:ru,gradFunc:n=>({x:()=>Xt(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const A7={kernelName:iu,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{clipValueMin:r,clipValueMax:i}=t;return{x:()=>zs(Ao(Ml(s,r),qu(s,i)),n,Xt(n))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const R7={kernelName:ld,inputsToSave:["x"],gradFunc:H4.gradFunc};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const M7={kernelName:cd,saveAllInputs:!0,gradFunc:(n,e,t)=>{const s=e.map(l=>l.shape),{axis:r}=t,i=It(r,e[0].shape)[0],o=s.map(l=>l[i]);return kr(n,o,i).map(l=>()=>l)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const N7={kernelName:ud,inputsToSave:["x","filter"],gradFunc:(n,e,t)=>{const[s,r]=e,{dilations:i,strides:o,pad:a,dataFormat:l}=t;return N(fl(i),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${i}'`),{x:()=>D2(s.shape,n,r,o,a,l),filter:()=>nv(s,n,r.shape,o,a,l)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $7={kernelName:hd,inputsToSave:["dy","filter"],gradFunc:(n,e,t)=>{const[s,r]=e,{strides:i,pad:o,dataFormat:a,dimRoundingMode:l}=t;return{dy:()=>gl(n,r,i,o,a,1,l),filter:()=>nv(n,s,r.shape,i,o,a,l)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function D7(n,e,t,s,r){let i=n;n.rank===4&&(i=se(n,[1,n.shape[0],n.shape[1],n.shape[2],n.shape[3]]));let o=e;o.rank===4&&(o=se(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]])),N(i.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${i.shape}.`),N(o.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${o.shape}.`),N(t.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${t}.`),N(i.shape[4]===t[3],()=>`Error in conv3dDerFilter: depth of input ${i.shape[4]}) must match input depth in filter (${t[3]}.`),N(o.shape[4]===t[4],()=>`Error in conv3dDerFilter: depth of dy (${o.shape[4]}) must match output depth for filter (${t[4]}).`);const a={x:i,dy:o},l={strides:s,pad:r,filterShape:t};return ee.runKernel(A0,a,l)}const P7=ie({conv3DBackpropFilter_:D7});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const L7={kernelName:dd,inputsToSave:["x","filter"],gradFunc:(n,e,t)=>{const{dilations:s,strides:r,pad:i}=t;N(fl(s),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);const[o,a]=e;return{x:()=>zC(o.shape,n,a,r,i),filter:()=>P7(o,n,a.shape,r,i)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const F7={kernelName:ou,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Z(Bn(s4(qe(t,"float32"))),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const O7={kernelName:au,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Z(r4(qe(t,"float32")),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const z7={kernelName:pd,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{axis:r,exclusive:i,reverse:o}=t;return{x:()=>{const a=ln([r],s.rank);let l=UC(n,r,i,!o);return a!=null&&(l=qt(l,a)),l}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const B7={kernelName:fd,inputsToSave:["x","filter"],gradFunc:(n,e,t)=>{const{dilations:s,strides:r,pad:i,dimRoundingMode:o}=t,a=s??[1,1];N(fl(a),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);const[l,c]=e;return N(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),N(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`),N(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]}.`),N(gs(r,a),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${a}'.`),or("depthwiseConv2d",i,o),{x:()=>K$(l.shape,n,c,r,i,a,o),filter:()=>q$(l,n,c.shape,r,i,a,o)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const U7={kernelName:md,inputsToSave:["x","filter"],gradFunc:(n,e,t)=>{const[s,r]=e,i={x:s,filter:r,dy:n},o={x:s,filter:r,dy:n};return{x:()=>ee.runKernel(Rf,i,t),filter:()=>ee.runKernel(Mf,o,t)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const V7={kernelName:cu,outputsToSave:[!0],gradFunc:(n,e)=>{const[t]=e,s={dy:n,y:t};return{x:()=>ee.runKernel(O0,s)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const W7={kernelName:uu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e,s=Z(Yi(Bn(yn(t))),2/Math.sqrt(Math.PI));return{x:()=>Z(n,s)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const G7={kernelName:hu,outputsToSave:[!0],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Z(n,t)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const H7={kernelName:xd,inputsToSave:["input"],gradFunc:(n,e)=>{const[t]=e;return{input:()=>se(n,t.shape)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const q7={kernelName:du,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Z(n,Yi(t))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const X7={kernelName:pu,gradFunc:n=>({x:()=>Xt(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const K7={kernelName:fu,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=pt(t.shape,s.shape);return{a:()=>{const a=ut(n,qe(s,"float32")),l=rs(t.shape,r);return l.length>0?se(lt(a,l),t.shape):a},b:()=>{let a=Z(n,qe(t,"float32"));const l=rs(s.shape,r);l.length>0&&(a=se(lt(a,l),s.shape));const c=yn(s);return Bn(ut(a,qe(c,"float32")))}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const j7={kernelName:vd,inputsToSave:["x","mean","variance","scale"],gradFunc:(n,e,t)=>{const{varianceEpsilon:s}=t,[r,i,o,a]=e,l=a??Ht(1),c=rs(i.shape,r.shape),u=[];if(i.rank===1){for(let y=0;yi.rank===1?se(Z(Z(n,gi(se(p,[1,1,1,i.shape[0]]),u)),l),r.shape):se(Z(Z(n,p),l),r.shape),mean:()=>{let y=Z(Z(p,Ht(-1)),d);return i.rank===1&&(y=lt(y,c)),se(y,i.shape)},variance:()=>{let y=Z(Z(f,h),d);return i.rank===1&&(y=lt(y,c)),se(y,i.shape)},scale:()=>{const y=Z(h,p);let w=Z(n,y);return i.rank===1&&(w=lt(w,c)),se(w,i.shape)},offset:()=>{let y=n;return i.rank===1&&(y=lt(y,c)),se(y,i.shape)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Y7={kernelName:bd,inputsToSave:["x","indices"],gradFunc:(n,e,t)=>{const[s,r]=e,{axis:i,batchDims:o}=t,a=It(i,s.shape)[0],l=(c,u,h)=>()=>{const d=c.shape,p=u.size,f=d.slice(0,a),x=f.length,m=d.slice(i,d.length).slice(1),g=m.length,v=fy(0,x),b=fy(x+1,x+1+g),y=my([f,[p],m]),w=se(h,y),C=se(u,[p]),T=my([[x],v,b]),E=qt(w,T);let R=l4(E,C,c.shape[a]);const _=no(T);return R=qt(R,_),R};if(o===1){const c=s.shape[0],u=s.split(c,0);return{x:()=>Ji(u.map((p,f)=>l(p,r.slice(f,1),n.slice(f,1))())).reshape(s.shape),indices:()=>r}}else return{x:l(s,r,n),indices:()=>r}}};function fy(n,e){const t=[];for(let s=n;s{const[t,s]=e;return{a:()=>Xt(t),b:()=>Xt(s)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const J7={kernelName:gu,gradFunc:n=>({x:()=>qe(n,"float32")})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Q7={kernelName:xu,gradFunc:n=>({x:()=>Xt(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eP={kernelName:vu,gradFunc:n=>({x:()=>Xt(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tP={kernelName:bu,gradFunc:n=>({x:()=>Xt(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nP={kernelName:wd,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{alpha:r}=t,i=Dr(s,0);return{x:()=>zs(i,n,Z(n,r))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const sP={kernelName:wu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ut(n,ke(t,1))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rP={kernelName:yu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ut(n,qe(t,"float32"))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iP={kernelName:$R,inputsToSave:[],outputsToSave:[!0],gradFunc:(n,e,t)=>{const[s]=e,{axis:r}=t;return{logits:()=>{const o=Yi(s);return ft(n,Z(lt(n,r,!0),o))}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oP(n,e,t,s=5,r=1,i=1,o=.5){const a={x:n,y:e,dy:t},l={depthRadius:s,bias:r,alpha:i,beta:o};return ee.runKernel(G0,a,l)}const aP=ie({localResponseNormalizationBackprop_:oP});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const lP={kernelName:Ed,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const[s,r]=e,{depthRadius:i,bias:o,alpha:a,beta:l}=t;return{x:()=>aP(s,r,n,i,o,a,l)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function q4(n,e,t,s){return e.rankZ(n,qe(ji(t,e),n.dtype))}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gy={kernelName:kd,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const s=t,{reductionIndices:r}=s,i=e[0],o=e[1],a=It(r,i.shape),l=q4(n,o,i,a);return{x:()=>l.x()}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cP={kernelName:Su,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e;return{a:()=>Z(n,qe(Ml(t,s),"float32")),b:()=>Z(n,qe(Lf(t,s),"float32"))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function uP(n,e,t,s,r,i,o){const a=G(n,"dy","maxPool3dGrad"),l=G(e,"input","maxPool3dGrad"),c=G(t,"output","maxPool3dGrad");let u=a,h=l,d=c,p=!1;l.rank===4&&(p=!0,u=se(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]]),h=se(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),d=se(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),N(u.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),N(h.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`),N(d.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${d.rank}.`),or("maxPool3dGrad",i,o);const f={dy:u,input:h,output:d},x={filterSize:s,strides:r,pad:i,dimRoundingMode:o},m=ee.runKernel(q0,f,x);return p?se(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}const hP=ie({maxPool3dGrad_:uP});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dP={kernelName:Rd,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const[s,r]=e,{filterSize:i,strides:o,pad:a,dimRoundingMode:l}=t;return{x:()=>hP(n,s,r,i,o,a,l)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pP(n,e,t,s,r,i,o){const a=G(n,"dy","maxPoolGrad"),l=G(e,"input","maxPoolGrad"),c=G(t,"output","maxPoolGrad");N(l.rank===a.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${a.rank})`),N(a.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${a.rank}.`),N(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),or("maxPoolGrad",i,o);const u={dy:a,input:l,output:c},h={filterSize:s,strides:r,pad:i,dimRoundingMode:o};return ee.runKernel(H0,u,h)}const fP=ie({maxPoolGrad_:pP});/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mP={kernelName:Ad,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const[s,r]=e,{filterSize:i,strides:o,pad:a}=t;return{x:()=>fP(n,s,r,i,o,a)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gP={kernelName:Md,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{axis:r}=t,i=It(r,s.shape),a=Wn(s.shape,i)[1],l=re(a);return{x:()=>{const u=s.shape.slice();i.forEach(p=>{u[p]=1});const h=se(n,u);return ut(Z(h,_a(s.shape,"float32")),l)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xP={kernelName:Nd,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,e,t)=>{const s=t,{axis:r}=s,[i,o]=e,a=It(r,i.shape),l=q4(n,o,i,a);return{x:()=>l.x()}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vP={kernelName:Cu,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e;return{a:()=>Z(n,qe(qu(t,s),"float32")),b:()=>Z(n,qe(Dr(t,s),"float32"))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bP={kernelName:$d,inputsToSave:["x"],gradFunc:(n,e,t)=>{const s=e[0],{paddings:r}=t,i=r.map(o=>o[0]);return{x:()=>fn(n,i,s.shape)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yP={kernelName:_u,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=pt(t.shape,s.shape);return{a:()=>{const a=rs(t.shape,r);return a.length>0?se(lt(n,a),t.shape):n},b:()=>{const a=Z(n,Bn(pm(ut(t,s)))),l=rs(s.shape,r);return l.length>0?se(lt(a,l),s.shape):a}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wP={kernelName:Tu,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=pt(t.shape,s.shape);return{a:()=>{const a=Z(n,qe(s,"float32")),l=rs(t.shape,r);return l.length>0?se(lt(a,l),t.shape):a},b:()=>{const a=Z(n,qe(t,"float32")),l=rs(s.shape,r);return l.length>0?se(lt(a,l),s.shape):a}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const SP={kernelName:Dd,gradFunc:n=>({x:()=>Bn(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const CP={kernelName:Fd,inputsToSave:["indices"],gradFunc:(n,e)=>{const t=e[0];return{indices:()=>On(t.shape,"float32")}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _P={kernelName:Ld,gradFunc:n=>({x:()=>Xt(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const TP={kernelName:Od,saveAllInputs:!0,gradFunc:(n,e,t)=>{const{axis:s}=t;return bl(n,s).map(i=>()=>i)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xy={kernelName:zd,inputsToSave:["x"],gradFunc:(n,e,t)=>{const s=e[0],{paddings:r}=t,i=r.map(o=>o[0]);return{x:()=>fn(n,i,s.shape)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const IP={kernelName:Iu,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(n,e)=>{const[t,s,r]=e,i=t,o=s,a=pt(i.shape,o.shape);return{a:()=>{const u=qe(o,"float32");let h=Z(n,Z(u,xl(i,ft(u,Ht(1)))));const d=rs(i.shape,a);return d.length>0&&(h=lt(h,d)),se(h,i.shape)},b:()=>{const u=Dr(i,0),h=zs(u,Zi(i),Xt(i));let d=Z(n,Z(r,h));const p=rs(o.shape,a);return p.length>0&&(d=lt(d,p)),se(d,o.shape)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const EP={kernelName:Bd,inputsToSave:["x","alpha"],gradFunc:(n,e)=>{const[t,s]=e,r=Dr(t,0);return{x:()=>zs(r,n,Z(n,s)),alpha:()=>{let i=zs(r,Xt(n),Z(n,t));const o=rs(s.shape,n.shape);return o.length>0&&(i=lt(i,o)),se(i,s.shape)}}}};/** + * @license + * Copyright 2022 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kP(n,e,t){const s=n.shape.slice();s[t]=1;const r=se(e,s),i=ax(n,t,!0,!1),o=ax(n,t,!0,!0),a=Z(i,o);return Z(r,a)}function AP(n,e,t){const s=n.shape.length,r=s-t.length,i=ln(t,s);let o=n;i!=null&&(o=qt(n,i));const a=o.shape.slice(),c=a.splice(s-t.length,t.length).reduce((d,p)=>d*p,1);a.push(c);const u=o.reshape(a);let h=kP(u,e,r);if(h=h.reshape(o.shape),i!=null){const d=no(i);h=qt(h,d)}return h}const RP={kernelName:Ud,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{axis:r}=t;let i=[];return r==null?i=s.shape.map((o,a)=>a):typeof r=="number"?i=[r]:i=r,{x:()=>AP(s,n,i)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const MP={kernelName:lu,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=pt(t.shape,s.shape);return{a:()=>{const a=ut(n,qe(s,"float32")),l=rs(t.shape,r);return l.length>0?se(lt(a,l),t.shape):a},b:()=>{let a=Z(n,qe(t,"float32"));const l=rs(s.shape,r);l.length>0&&(a=se(lt(a,l),s.shape));const c=yn(s);return Bn(ut(a,qe(c,"float32")))}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const NP={kernelName:Eu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ut(n,Bn(yn(t)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $P={kernelName:Au,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e,s=Z(qu(t,6),rp(t));return{x:()=>Z(n,qe(s,"float32"))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const DP={kernelName:ku,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Z(n,qe(rp(t),"float32"))}}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const PP={kernelName:Vd,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>se(n,t.shape)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const LP={kernelName:Gd,inputsToSave:["images"],gradFunc:(n,e,t)=>{const[s]=e,r={dy:n,images:s};return{images:()=>ee.runKernel(J0,r,t)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const FP={kernelName:Wd,inputsToSave:["images"],gradFunc:(n,e,t)=>{const[s]=e,r={dy:n,images:s};return{images:()=>ee.runKernel(Z0,r,t)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const OP={kernelName:Hd,gradFunc:(n,e,t)=>{const{dims:s}=t,r=It(s,n.shape);return{x:()=>vl(n,r)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const zP={kernelName:Ru,gradFunc:n=>({x:()=>Xt(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const BP={kernelName:Mu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Bn(ut(n,Z(xl(t,1.5),2)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const UP={kernelName:qd,inputsToSave:["condition"],gradFunc:(n,e)=>{const[t]=e;return{condition:()=>qe(Xt(t),"float32"),t:()=>Z(n,qe(t,n.dtype)),e:()=>Z(n,qe(U2(t),n.dtype))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const VP={kernelName:Nu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>{const s=Dr(t,Ht(0)),r=Ht(ip),i=Ht(op),o=Z(n,i),a=Z(Z(n,r),Yi(qe(t,"float32")));return zs(s,o,a)}}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const WP={kernelName:Lu,outputsToSave:[!0],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Z(n,Z(t,ft(Ht(1),t)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const GP={kernelName:Pu,gradFunc:n=>({x:()=>Xt(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const HP={kernelName:$u,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Z(P2(qe(t,"float32")),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qP={kernelName:Du,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Z(BC(qe(t,"float32")),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const XP={kernelName:Xd,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{begin:r,size:i}=t,o=s.shape,[a,l]=vm(s,r,i),c=[];for(let u=0;uG2(n,c)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const KP={kernelName:Zd,outputsToSave:[!0],gradFunc:(n,e,t)=>{const[s]=e,{dim:r}=t,i=!0,o=Z(n,s);return{logits:()=>ft(o,Z(lt(o,[r],i),s))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const jP={kernelName:Fu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Z(n,Hu(t))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vy={kernelName:jd,gradFunc:(n,e,t)=>{const{blockShape:s,paddings:r}=t;return{x:()=>$2(n,s,r)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const by={kernelName:Yd,gradFunc:(n,e,t)=>{const{axis:s}=t;return{x:()=>tr(n,s)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const YP={kernelName:Ou,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ut(n,Z(As(qe(t,"float32")),2))}}};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ZP={kernelName:Q0,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Z(n,Z(qe(t,"float32"),2))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const JP={kernelName:zu,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=Ht(2);return{a:()=>Z(n,Z(r,ft(t,s))),b:()=>Z(n,Z(r,ft(s,t)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const QP={kernelName:Gu,gradFunc:n=>({x:()=>Xt(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const e8={kernelName:Bu,inputsToSave:["a","b"],gradFunc:(n,e)=>{const[t,s]=e,r=pt(t.shape,s.shape);return{a:()=>{let a=n;const l=rs(t.shape,r);return l.length>0&&(a=lt(a,l)),se(a,t.shape)},b:()=>{let a=n;const l=rs(s.shape,r);return l.length>0&&(a=lt(a,l)),se(Bn(a),s.shape)}}}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const t8={kernelName:Kd,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,r=s.shape.slice(),{axis:i}=t;It(i,s.shape).forEach(c=>{r[c]=1});const a=se(n,r),l=Z(a,_a(s.shape,"float32"));return{x:()=>l}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const n8={kernelName:Uu,inputsToSave:["x"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>ut(n,yn(P2(t)))}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const s8={kernelName:Vu,outputsToSave:[!0],gradFunc:(n,e)=>{const[t]=e;return{x:()=>Z(ft(Ht(1),yn(t)),n)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const r8={kernelName:Wu,inputsToSave:["x"],gradFunc:(n,e,t)=>{const[s]=e,{reps:r}=t;return{x:()=>{let o=Xt(s);if(s.rank===1)for(let a=0;a{const s=t,{perm:r}=s,i=no(r);return{x:()=>qt(n,i)}}};/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const o8={kernelName:Jd,gradFunc:(n,e,t)=>{const s=t,{axis:r}=s;return{value:()=>Ji(n,r)}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const a8={kernelName:Qd,inputsToSave:["segmentIds"],gradFunc:(n,e)=>{const[t]=e;return{x:()=>l8(n,t)}}};function l8(n,e){const t=Ca(e,Xt(e)),s=O2(n,t);let r=Ml(e,Ht(0,"int32"));const i=s.rank-r.rank;for(let a=0;a({x:()=>Xt(n)})};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const u8=[H4,a7,l7,c7,u7,h7,d7,p7,f7,m7,g7,x7,y7,C7,_7,T7,I7,E7,k7,A7,R7,M7,$7,N7,L7,F7,O7,z7,B7,U7,MP,V7,W7,G7,H7,q7,K7,X7,j7,Y7,Z7,J7,Q7,eP,tP,nP,sP,rP,iP,lP,gy,gy,cP,dP,mP,gP,xP,vP,bP,yP,wP,SP,CP,_P,TP,xy,xy,IP,EP,RP,NP,$P,DP,PP,LP,FP,OP,zP,BP,UP,VP,WP,GP,HP,qP,XP,KP,jP,vy,vy,by,by,YP,JP,ZP,QP,e8,t8,n8,s8,r8,i8,o8,a8,c8];for(const n of u8)DR(n);/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.abs=function(){return this.throwIfDisposed(),Ls(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.acos=function(){return this.throwIfDisposed(),BM(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.acosh=function(){return this.throwIfDisposed(),VM(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.add=function(n){return this.throwIfDisposed(),ke(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.all=function(n,e){return this.throwIfDisposed(),LC(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.any=function(n,e){return this.throwIfDisposed(),ix(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.argMax=function(n){return this.throwIfDisposed(),Fh(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.argMin=function(n){return this.throwIfDisposed(),XM(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.asScalar=function(){return this.throwIfDisposed(),N(this.size===1,()=>"The array must have only 1 element."),se(this,[])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.asType=function(n){return this.throwIfDisposed(),qe(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.as1D=function(){return this.throwIfDisposed(),se(this,[this.size])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.as2D=function(n,e){return this.throwIfDisposed(),se(this,[n,e])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.as3D=function(n,e,t){return this.throwIfDisposed(),se(this,[n,e,t])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.as4D=function(n,e,t,s){return this.throwIfDisposed(),se(this,[n,e,t,s])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.as5D=function(n,e,t,s,r){return this.throwIfDisposed(),se(this,[n,e,t,s,r])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.asin=function(){return this.throwIfDisposed(),jM(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.asinh=function(){return this.throwIfDisposed(),ZM(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.atan=function(){return this.throwIfDisposed(),QM(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.atan2=function(n){return this.throwIfDisposed(),tN(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.atanh=function(){return this.throwIfDisposed(),sN(this)};me().prototype.avgPool=function(n,e,t,s){return this.throwIfDisposed(),N2(this,n,e,t,s)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.batchToSpaceND=function(n,e){return this.throwIfDisposed(),$2(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.batchNorm=function(n,e,t,s,r){return this.throwIfDisposed(),cm(this,n,e,t,s,r)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.broadcastTo=function(n){return this.throwIfDisposed(),Mh(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.cast=function(n){return this.throwIfDisposed(),qe(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.ceil=function(){return this.throwIfDisposed(),RN(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.clipByValue=function(n,e){return this.throwIfDisposed(),Mr(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.concat=function(n,e){return this.throwIfDisposed(),n instanceof Yn&&(n=[n]),tr([this,...n],e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.conv1d=function(n,e,t,s,r,i){return this.throwIfDisposed(),FC(this,n,e,t,s,r,i)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.conv2dTranspose=function(n,e,t,s,r){return this.throwIfDisposed(),OC(this,n,e,t,s,r)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.conv2d=function(n,e,t,s,r,i){return this.throwIfDisposed(),gl(this,n,e,t,s,r,i)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.cos=function(){return this.throwIfDisposed(),P2(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.cosh=function(){return this.throwIfDisposed(),BC(this)};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.cumprod=function(n,e,t){return this.throwIfDisposed(),ax(this,n,e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.cumsum=function(n,e,t){return this.throwIfDisposed(),UC(this,n,e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.depthToSpace=function(n,e){return this.throwIfDisposed(),t5(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.depthwiseConv2d=function(n,e,t,s,r,i){return this.throwIfDisposed(),L2(this,n,e,t,s,r,i)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.dilation2d=function(n,e,t,s,r){return this.throwIfDisposed(),r5(this,n,e,t,s,r)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.divNoNan=function(n){return this.throwIfDisposed(),c5(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.div=function(n){return this.throwIfDisposed(),ut(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.dot=function(n){return this.throwIfDisposed(),h5(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.elu=function(){return this.throwIfDisposed(),hm(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.equal=function(n){return this.throwIfDisposed(),ji(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.erf=function(){return this.throwIfDisposed(),VC(this)};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.euclideanNorm=function(n,e){return this.throwIfDisposed(),C5(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.exp=function(){return this.throwIfDisposed(),Yi(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.expandDims=function(n){return this.throwIfDisposed(),js(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.expm1=function(){return this.throwIfDisposed(),E5(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.fft=function(){return this.throwIfDisposed(),o4(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.flatten=function(){return this.throwIfDisposed(),se(this,[this.size])};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.floor=function(){return this.throwIfDisposed(),pm(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.floorDiv=function(n){return this.throwIfDisposed(),PC(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.gather=function(n,e,t){return this.throwIfDisposed(),O2(this,n,e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.greaterEqual=function(n){return this.throwIfDisposed(),Ml(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.greater=function(n){return this.throwIfDisposed(),Dr(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.ifft=function(){return this.throwIfDisposed(),lx(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.irfft=function(){return this.throwIfDisposed(),v$(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.isFinite=function(){return this.throwIfDisposed(),L5(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.isInf=function(){return this.throwIfDisposed(),O5(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.isNaN=function(){return this.throwIfDisposed(),B5(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.leakyRelu=function(n){return this.throwIfDisposed(),B2(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.lessEqual=function(n){return this.throwIfDisposed(),qu(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.less=function(n){return this.throwIfDisposed(),Lf(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.localResponseNormalization=function(n,e,t,s){return this.throwIfDisposed(),H5(this,n,e,t,s)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.logSigmoid=function(){return this.throwIfDisposed(),J5(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.logSoftmax=function(n){return this.throwIfDisposed(),fm(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.logSumExp=function(n,e){return this.throwIfDisposed(),XC(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.log=function(){return this.throwIfDisposed(),Zi(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.log1p=function(){return this.throwIfDisposed(),qC(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.logicalAnd=function(n){return this.throwIfDisposed(),Ao(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.logicalNot=function(){return this.throwIfDisposed(),U2(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.logicalOr=function(n){return this.throwIfDisposed(),KC(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.logicalXor=function(n){return this.throwIfDisposed(),o6(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.matMul=function(n,e,t){return this.throwIfDisposed(),Jt(this,n,e,t)};me().prototype.maxPool=function(n,e,t,s){return this.throwIfDisposed(),V2(this,n,e,t,s)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.max=function(n,e){return this.throwIfDisposed(),wi(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.maximum=function(n){return this.throwIfDisposed(),Ca(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.mean=function(n,e){return this.throwIfDisposed(),Xn(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.min=function(n,e){return this.throwIfDisposed(),Pf(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.minimum=function(n){return this.throwIfDisposed(),Bh(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.mirrorPad=function(n,e){return this.throwIfDisposed(),f6(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.mod=function(n){return this.throwIfDisposed(),g6(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.mul=function(n){return this.throwIfDisposed(),Z(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.neg=function(){return this.throwIfDisposed(),Bn(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.norm=function(n,e,t){return this.throwIfDisposed(),dm(this,n,e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.notEqual=function(n){return this.throwIfDisposed(),Ff(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.oneHot=function(n,e=1,t=0){return this.throwIfDisposed(),jC(this,n,e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.onesLike=function(){return this.throwIfDisposed(),ti(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.pad=function(n,e){return this.throwIfDisposed(),G2(this,n,e)};me().prototype.pool=function(n,e,t,s,r,i){return this.throwIfDisposed(),I6(this,n,e,t,s,r,i)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.pow=function(n){return this.throwIfDisposed(),xl(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.prelu=function(n){return this.throwIfDisposed(),q2(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.prod=function(n,e){return this.throwIfDisposed(),A6(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.reciprocal=function(){return this.throwIfDisposed(),J6(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.relu=function(){return this.throwIfDisposed(),$l(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.relu6=function(){return this.throwIfDisposed(),JC(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.reshapeAs=function(n){return this.throwIfDisposed(),se(this,n.shape)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.reshape=function(n){return this.throwIfDisposed(),se(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.resizeBilinear=function(n,e,t){return this.throwIfDisposed(),u4(this,n,e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.resizeNearestNeighbor=function(n,e,t){return this.throwIfDisposed(),h4(this,n,e,t)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.reverse=function(n){return this.throwIfDisposed(),vl(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.rfft=function(){return this.throwIfDisposed(),w$(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.round=function(){return this.throwIfDisposed(),QC(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.rsqrt=function(){return this.throwIfDisposed(),e4(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.selu=function(){return this.throwIfDisposed(),t4(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.separableConv2d=function(n,e,t,s,r,i){return this.throwIfDisposed(),n4(this,n,e,t,s,r,i)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.sigmoid=function(){return this.throwIfDisposed(),Hu(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.sign=function(){return this.throwIfDisposed(),a$(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.sin=function(){return this.throwIfDisposed(),s4(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.sinh=function(){return this.throwIfDisposed(),r4(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.slice=function(n,e){return this.throwIfDisposed(),fn(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.softmax=function(n){return this.throwIfDisposed(),np(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.softplus=function(){return this.throwIfDisposed(),tp(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.spaceToBatchND=function(n,e){return this.throwIfDisposed(),H2(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.split=function(n,e){return this.throwIfDisposed(),kr(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.sqrt=function(){return this.throwIfDisposed(),As(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.square=function(){return this.throwIfDisposed(),yn(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.squaredDifference=function(n){return this.throwIfDisposed(),C$(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.squeeze=function(n){return this.throwIfDisposed(),sp(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.stack=function(n,e){this.throwIfDisposed();const t=n instanceof Yn?[this,n]:[this,...n];return Ji(t,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.step=function(n){return this.throwIfDisposed(),rp(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.stridedSlice=function(n,e,t,s,r,i,o,a){return this.throwIfDisposed(),k$(this,n,e,t,s,r,i,o,a)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.sub=function(n){return this.throwIfDisposed(),ft(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.sum=function(n,e){return this.throwIfDisposed(),lt(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.tan=function(){return this.throwIfDisposed(),R$(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.tanh=function(){return this.throwIfDisposed(),Nc(this)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.tile=function(n){return this.throwIfDisposed(),gi(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.toBool=function(){return this.throwIfDisposed(),qe(this,"bool")};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.toFloat=function(){return this.throwIfDisposed(),qe(this,"float32")};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.toInt=function(){return this.throwIfDisposed(),qe(this,"int32")};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.topk=function(n,e){return this.throwIfDisposed(),N$(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.transpose=function(n){return this.throwIfDisposed(),qt(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.unique=function(n){return this.throwIfDisposed(),P$(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.unsortedSegmentSum=function(n,e){return this.throwIfDisposed(),l4(this,n,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.unstack=function(n){return this.throwIfDisposed(),bl(this,n)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.where=function(n,e){return this.throwIfDisposed(),zs(n,this,e)};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */me().prototype.zerosLike=function(){return this.throwIfDisposed(),Xt(this)};/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Pi extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Pi.prototype)}}class Yr extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Yr.prototype)}}class Y extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Y.prototype)}}class Mt extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Mt.prototype)}}class xv extends Error{constructor(e){super(e),Object.setPrototypeOf(this,xv.prototype)}}/** + * @license + * Copyright 2022 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class X4{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){const s=this.cache.keys().next().value;this.cache.delete(s)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;tt.toUpperCase())}let Ur={};function vv(n){if(n==null)return null;const e={};return e.className=n.getClassName(),e.config=n.getConfig(),e}function hx(n){if(!(n==null||typeof n!="object"))if(Array.isArray(n))n.forEach(e=>hx(e));else{const e=Object.keys(n);for(const t of e){const s=n[t];s!=null&&typeof s=="object"&&(!Array.isArray(s)&&s.type==="ndarray"&&typeof s.value=="number"?n[t]=s.value:hx(s))}}}function ap(n,e={},t={},s="object",r=!1){if(typeof n=="string"){const i=n;let o;if(i in t)o=t[i];else if(i in Ur)o=Ur[i];else if(o=e[i],o==null)throw new Y(`Unknown ${s}: ${n}. This may be due to one of the following reasons: +1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code. +2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return o}else{const i=n;if(i.className==null||i.config==null)throw new Y(`${s}: Improper config format: ${JSON.stringify(i)}. +'className' and 'config' must set.`);const o=i.className;let a,l;if(o in t?[a,l]=t[o]:o in Ur?[a,l]=Ur.className:o in e&&([a,l]=e[o]),a==null)throw new Y(`Unknown ${s}: ${o}. This may be due to one of the following reasons: +1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code. +2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){const c={};for(const p of Object.keys(Ur))c[p]=Ur[p];for(const p of Object.keys(t))c[p]=t[p];const u=i.config;u.customObjects=c;const h=Object.assign({},Ur);for(const p of Object.keys(t))Ur[p]=t[p];hx(i.config);const d=l(a,i.config,t,r);return Ur=Object.assign({},h),d}else{const c=Object.assign({},Ur);for(const h of Object.keys(t))Ur[h]=t[h];const u=new a(i.config);return Ur=Object.assign({},c),u}}}function h8(n,e){return ne?1:0}function Np(n,e){return-1*h8(n,e)}function ta(n){if(n==null)return n;const e=[];for(const t of n)e.indexOf(t)===-1&&e.push(t);return e}function d8(n){if(n==null)throw new Y(`Invalid value in obj: ${JSON.stringify(n)}`);for(const e in n)if(n.hasOwnProperty(e))return!1;return!0}function Fl(n,e,t){if(t!=null&&n.indexOf(t)<0)throw new Y(`${t} is not a valid ${e}. Valid values are ${n} or null/undefined.`)}function bv(n,e,t=0,s=1/0){return Li(t>=0),Li(s>=t),Array.isArray(n)&&n.length>=t&&n.length<=s&&n.every(r=>typeof r===e)}function us(n,e){Array.isArray(n)?(N(n.length>0,()=>`${e} is unexpectedly an empty array.`),n.forEach((t,s)=>us(t,`element ${s+1} of ${e}`))):N(Number.isInteger(n)&&n>0,()=>`Expected ${e} to be a positive integer, but got ${K4(n)}.`)}function K4(n){return n===null?"null":Array.isArray(n)?"["+n.map(e=>K4(e)).join(",")+"]":typeof n=="string"?`"${n}"`:`${n}`}function p8(n,e,t){let s=t!=null?t():qs(),r;return(...o)=>{const a=t!=null?t():qs();return a-s0){const t=`${n}_${e}`;return Xl.set(t,1),t}else return n}const S8=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function e_(n){return!!n.match(S8)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function C8(n){return n===parseInt(n.toString(),10)}function na(n,e,t){e==null&&(e=0),t==null&&(t=n.length);let s=1;for(let r=e;re&&(e=s)}return e}function Ii(n,e){if(e{if(n.shape.length!==2)throw new Y(`repeat() expects a rank-2 tensor, but received a rank-${n.shape.length} tensor.`);const t=lp(n,1);return dx(t,[1,e,1])})}function T8(n){const e=[na(n.shape)];return se(n,e)}function I8(n){if(n.rank<=1)throw new Y(`batchFlatten requires a minimum rank of 2. Got rank: ${n.rank}.`);const e=[n.shape[0],na(n.shape,1)];return se(n,e)}function al(n,e,t){return le(()=>{switch(n.rank){case 1:return ev(n,e,t);case 2:return i4(n,[e,0],[t,n.shape[1]]);case 3:return tv(n,[e,0,0],[t,n.shape[1],n.shape[2]]);case 4:return zf(n,[e,0,0,0],[t,n.shape[1],n.shape[2],n.shape[3]]);case 5:return fn(n,[e,0,0,0,0],[t,n.shape[1],n.shape[2],n.shape[3],n.shape[4]]);case 6:return fn(n,[e,0,0,0,0,0],[t,n.shape[1],n.shape[2],n.shape[3],n.shape[4],n.shape[5]]);default:throw new Y(`sliceAlongFirstAxis() received an unsupported tensor rank: ${n.rank}`)}})}function $g(n,e,t){return le(()=>{switch(n.rank){case 1:return ev(n,e,t);case 2:return i4(n,[0,e],[n.shape[0],t]);case 3:return tv(n,[0,0,e],[n.shape[0],n.shape[1],t]);case 4:return zf(n,[0,0,0,e],[n.shape[0],n.shape[1],n.shape[2],t]);default:throw new Y(`sliceAlongLastAxis() received an unsupported tensor rank: ${n.rank}`)}})}function Dp(n,e,t,s){return le(()=>{switch(n.rank){case 1:return ev(n,e,t);case 2:switch(s){case 1:return al(n,e,t);case 2:return $g(n,e,t);default:throw new Y(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return al(n,e,t);case 2:return tv(n,[0,e,0],[n.shape[0],t,n.shape[2]]);case 3:return $g(n,e,t);default:throw new Y(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return al(n,e,t);case 2:return zf(n,[0,e,0,0],[n.shape[0],t,n.shape[2],n.shape[3]]);case 3:return zf(n,[0,0,e,0],[n.shape[0],n.shape[1],t,n.shape[3]]);case 4:return $g(n,e,t);default:throw new Y(`The axis is not within the rank of the tensor ${s}`)}default:throw new Y(`sliceAlongLastAxis() received an unsupported tensor rank: ${n.rank}`)}})}function yv(n,e=-1){let t;return e<0&&(t=n[0].rank,t!==0?e=t:e=0),e===n[0].rank&&(e=-1),tr(n,e)}function Sy(n,e){switch(n.rank){case 1:return $N([n,e]);case 2:return PN([n,e],0);case 3:return FN([n,e],0);case 4:return zN([n,e],0);default:throw new Y(`concatAlongFirstAxis() received an unsupported tensor rank: ${n.rank}`)}}function dx(n,e){if(Array.isArray(e)||(e=[e]),n.rank!==e.length)throw new Y(`The length of input n (${e.length}) does not match the number of dimensions in input x (${n.rank})`);return gi(n,e)}function Fm(n,e=0,t=1,s,r){return K6(n,e,t,s,r)}function qi(n,e,t,s){if(n.rank<2||e.rank<2)throw new Mt(`dot requires both inputs to be rank >= 2 but got x shape = ${n.shape} and y shape = ${e.shape}`);if(e.rank>=3){const r=n.shape.slice(-1)[0],i=e.shape.slice(-2)[0];if(r!==i)throw new Mt(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${n.shape} and y shape = ${e.shape}`)}if(n.rank===2&&e.rank===2)return iy({a:n,b:e,transposeA:!1,transposeB:!1,bias:s?px(n.rank,s,Ei()):null,activation:t});{const r=n.shape.slice(),i=r.pop();n=se(n,[-1,i]);const o=e.shape.slice(),a=o.pop(),l=o.pop(),c=[...o,a],u=Array.from({length:e.rank},(f,x)=>x===0?e.rank-2:x<=e.rank-2?x-1:x);e=se(qt(e,u),[l,-1]);const h=[...r,...c];return se(iy({a:n,b:e,transposeA:!1,transposeB:!1,bias:s?px(n.rank,s,Ei()):null,activation:t}),h)}}function t_(n,e,t){return le(()=>(Array.isArray(e)?e=Zs(e,"int32"):e=qe(e,"int32"),O2(n,e,t)))}function cp(n){return Z(n,n)}function px(n,e,t){const s=e.shape;if(e.rank!==1&&e.rank!==n)throw new Y(`Unexpected bias dimensions: ${e.rank}; expected it to be 1 or ${n}`);if(n===5){if(t==="channelsFirst")return s.length===1?se(e,[1,s[0],1,1,1]):se(e,[1,s[3],s[0],s[1],s[2]]);if(t==="channelsLast")return s.length===1?se(e,[1,1,1,1,s[0]]):se(e,[1].concat(s))}else if(n===4){if(t==="channelsFirst")return s.length===1?se(e,[1,s[0],1,1]):se(e,[1,s[2],s[0],s[1]]);if(t==="channelsLast")return s.length===1?se(e,[1,1,1,s[0]]):se(e,[1].concat(s))}else if(n===3){if(t==="channelsFirst")return s.length===1?se(e,[1,s[0],1]):se(e,[1,s[1],s[0]]);if(t==="channelsLast")return s.length===1?se(e,[1,1,s[0]]):se(e,[1].concat(s))}else if(n<3)return e;throw new Y(`Unsupported input rank by biasAdd: ${e.rank}`)}function Mi(n,e,t){return le(()=>(t==null&&(t=Ei()),Gn(t),ke(n,px(n.rank,e,t))))}function E8(n,e=1){if(e!==1)throw new Mt(`Support for alpha values other than 1 (${e}) is not implemented yet.`);return hm(n)}function k8(n){return le(()=>ut(n,ke(Ls(n),1)))}function n_(n,e,t,s){return le(()=>U$(n,e,t,s))}function A8(n){return le(()=>{const e=ke(.5,Z(.2,n));return Mr(e,0,1)})}function up(n,e,t=!1){return t?n():e()}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const R8=["fanIn","fanOut","fanAvg"],M8=["normal","uniform","truncatedNormal"];/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function N8(n){Fl(R8,"FanMode",n)}function $8(n){Fl(M8,"Distribution",n)}class si extends Ku{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class s_ extends si{apply(e,t){return On(e,t)}}s_.className="Zeros";we(s_);class wv extends si{apply(e,t){return _a(e,t)}}wv.className="Ones";we(wv);class r_ extends si{constructor(e){if(super(),typeof e!="object")throw new Y(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new Y(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return le(()=>Z(Ht(this.value),_a(e,t)))}getConfig(){return{value:this.value}}}r_.className="Constant";we(r_);class i_ extends si{constructor(e){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return aa(e,this.minval,this.maxval,t,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}i_.className="RandomUniform";we(i_);class o_ extends si{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Mt(`randomNormal does not support dType ${t}.`);return Fm(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}o_.className="RandomNormal";we(o_);class a_ extends si{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Mt(`truncatedNormal does not support dType ${t}.`);return a4(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}a_.className="TruncatedNormal";we(a_);class l_ extends si{constructor(e){super(),this.gain=e.gain!=null?e.gain:1}apply(e,t){return le(()=>{if(e.length!==2||e[0]!==e[1])throw new Y("Identity matrix initializer can only be used for 2D square matrices.");return Z(this.gain,HC(e[0]))})}getConfig(){return{gain:this.gain}}}l_.className="Identity";we(l_);function D8(n,e="channelsLast"){let t,s;if(Gn(e),n.length===2)t=n[0],s=n[1];else if([3,4,5].indexOf(n.length)!==-1){if(e==="channelsFirst"){const r=na(n,2);t=n[1]*r,s=n[0]*r}else if(e==="channelsLast"){const r=na(n,0,n.length-2);t=n[n.length-2]*r,s=n[n.length-1]*r}}else{const r=na(n);t=Math.sqrt(r),s=Math.sqrt(r)}return[t,s]}class xr extends si{constructor(e){if(super(),e.scale<0)throw new Y(`scale must be a positive float. Got: ${e.scale}`);this.scale=e.scale==null?1:e.scale,this.mode=e.mode==null?"fanIn":e.mode,N8(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,$8(this.distribution),this.seed=e.seed}apply(e,t){const s=D8(e),r=s[0],i=s[1];let o=this.scale;if(this.mode==="fanIn"?o/=Math.max(1,r):this.mode==="fanOut"?o/=Math.max(1,i):o/=Math.max(1,(r+i)/2),this.distribution==="normal"){const a=Math.sqrt(o);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Mt(`${this.getClassName()} does not support dType ${t}.`);return a4(e,0,a,t,this.seed)}else{const a=Math.sqrt(3*o);return aa(e,-a,a,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}xr.className="VarianceScaling";we(xr);class Sv extends xr{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return xr.className}}Sv.className="GlorotUniform";we(Sv);class Cv extends xr{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return xr.className}}Cv.className="GlorotNormal";we(Cv);class _v extends xr{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return xr.className}}_v.className="HeNormal";we(_v);class Tv extends xr{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return xr.className}}Tv.className="HeUniform";we(Tv);class Iv extends xr{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return xr.className}}Iv.className="LeCunNormal";we(Iv);class Ev extends xr{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return xr.className}}Ev.className="LeCunUniform";we(Ev);class c_ extends si{constructor(e){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed}apply(e,t){return le(()=>{if(e.length<2)throw new Mt("Shape must be at least 2D.");if(t!=="int32"&&t!=="float32"&&t!==void 0)throw new TypeError(`Unsupported data type ${t}.`);t=t;const s=re(e.slice(0,-1)),r=e[e.length-1],i=s*r;i>this.ELEMENTS_WARN_SLOW&&console.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${i}) elements: Slowness may result.`);const o=[Math.max(r,s),Math.min(r,s)],a=Fm(o,0,1,t,this.seed),l=FD.qr(a,!1);let c=l[0];const h=l[1].flatten().stridedSlice([0],[Math.min(r,s)*Math.min(r,s)],[Math.min(r,s)+1]);return c=Z(c,h.sign()),ss*r);return e}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const Ty="Variable";class P8{constructor(e,t="float32",s=Ty,r=!0,i=null){this.dtype=t??"float32",this.shape=e.shape,this.id=Y4(),s=s??Ty,this.originalName=J4(s),this.name=Q4(this.originalName),this.trainable_=r,this.constraint=i,this.val=tl(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),L8(this.val,e),this.val.id!==e.id&&(this.val.assign(e),this.constraint!=null&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}}function L8(n,e){if(n.shape.toString()!==e.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(n.shape)+" vs. "+JSON.stringify(e.shape))}function mx(n){return n.map(e=>e.read())}function kv(n){n.forEach(e=>{e[0].write(e[1])})}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Jn{constructor(e){this.dtype=e.dtype,this.shape=e.shape,e.shape!=null?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class Qi{constructor(e,t,s,r,i,o,a){this.dtype=e,this.shape=t,this.sourceLayer=s,this.inputs=r,this.callArgs=i,this.outputTensorIndex=a,this.id=Y4(),o!=null&&(this.originalName=J4(o),this.name=Q4(this.originalName)),this.rank=t.length}}let F8=0;class Om{constructor(e,t){this.callArgs=t,this.id=F8++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const s of e.inboundLayers)s?.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)t!=null?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let O8=0;class Ot extends Ku{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=O8++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const s=this.getClassName();t=xo(s)+"_"+Lm(s)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let s;if(e.batchInputShape!=null)s=e.batchInputShape;else if(e.inputShape!=null){let i=null;e.batchSize!=null&&(i=e.batchSize),s=[i].concat(e.inputShape)}this.batchInputShape=s;let r=e.dtype;r==null&&(r=e.inputDType),r==null&&(r="float32"),this.dtype=r}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new Yr(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new Y(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Ys(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Ys(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Pi(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(this.inboundNodes.length===0)throw new Pi(`Layer ${this.name} is not connected, no input to return.`);return Ys(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new Pi(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Pi(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Ys(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){const t=nn(e);if(this.inputSpec==null||this.inputSpec.length===0)return;const s=nn(this.inputSpec);if(t.length!==s.length)throw new Y(`Layer ${this.name} expects ${s.length} inputs, but it received ${t.length} input tensors. Input received: ${e}`);for(let r=0;ro.maxNDim)throw new Y(`Input ${r} is incompatible with layer ${this.name}: expected max_ndim=${o.maxNDim}, found ndim=${a}`);if(o.minNDim!=null&&a=0?l[u]:l[l.length+u];if(h!=null&&[h,null].indexOf(d)===-1)throw new Y(`Input ${r} is incompatible with layer ${this.name}: expected axis ${u} of input shape to have value ${h} but got shape ${l}.`)}}if(o.shape!=null)for(let l=0;l{if(!this.built){this.assertInputCompatibility(e);const o=[];for(const a of nn(e))o.push(a.shape);this.build(Ys(o)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&i&&(this._refCount=1)}if(this.assertInputCompatibility(e),i){let o=this.call(e,t);this.supportsMasking&&this.setMaskMetadata(e,o);const a=nn(o),l=[];for(let c of a)s.indexOf(c)!==-1&&(c=c.clone()),l.push(c);if(o=Ys(l),this.activityRegularizer!=null)throw new Mt("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return o}else{const o=z8(e),a=this.computeOutputShape(o);let l;const c=B8(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?o[0]:o),a!=null&&a.length>0&&Array.isArray(a[0])?l=a.map((u,h)=>new Qi(c,u,this,nn(e),t,this.name,h)):l=new Qi(c,a,this,nn(e),t,this.name),this.addInboundNode(e,l,null,null,o,a,t),this._refCount++,this.activityRegularizer!=null)throw new Mt("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return l}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)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((s,r)=>{s!=null&&e[r]!=null&&e[r]!==s&&(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(this.inboundNodes==null||this.inboundNodes.length===0)throw new Pi(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const s=JSON.stringify(t.outputShapes);e.indexOf(s)===-1&&e.push(s)}if(e.length===1){const t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}else throw new Pi(`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 Yr(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Uf(this.weights)}build(e){this.built=!0}getWeights(e=!1){return mx(e?this.trainableWeights:this.weights)}setWeights(e){le(()=>{const t=this.weights;if(t.length!==e.length)throw new Y(`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(t.length===0)return;const s=[],r=mx(t);for(let i=0;ii.apply(u.read())),o==null&&(o=!0),o?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=nn(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.forEach(s=>{if(s!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return t}setMaskMetadata(e,t,s){if(!this.supportsMasking)return;const r=this.computeMask(e,s),i=nn(t),o=nn(r);if(i.length!==o.length)throw new Error(`${this.name} outputs ${i.length} tensors but ${i.length} masks for those tensors`);for(let a=0;ae.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)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(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return--this._refCount===0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function z8(n){n=nn(n);const e=[];for(const t of n)e.push(t.shape);return Ys(e)}function B8(n){return"float32"}function u_(n,e,t){if((e==null||t!=null&&t>0)&&(e=n.sourceLayer,t=n.nodeIndex),e.inboundNodes.length===0)return[n];{const s=e.inboundNodes[t];if(s.inboundLayers.length===0)return s.inputTensors;{const r=[];for(let i=0;if.name),l=[],c=e.names();for(const f of a)c.indexOf(f)!==-1?l.push(e.getValue(f)):l.push(null);const u=a.join(",")+"|"+e.names().sort().join(",");let h=Vf.get(u),d;if(h==null){const f=q8(o,e);h=f.sorted,d=f.recipientCounts,Vf.put(u,h),Wf.put(u,d)}d={},r||Object.assign(d,Wf.get(u));const p=new jo(e);for(let f=0;f0,()=>"Expected at least one fetch, got none");let t=[],s={};if(n.length===1){const r=Iy(n[0],e);t=r.sorted,s=r.recipientMap}else{const r=new Set;for(const i of n){const{sorted:o,recipientMap:a}=Iy(i,e);for(const l of o)r.has(l.name)||(t.push(l),r.add(l.name));for(const l in a)s[l]==null&&(s[l]=new Set),a[l].forEach(c=>s[l].add(c))}}return{sorted:t,recipientCounts:X8(s)}}function X8(n){const e={};for(const t in n)e[t]=n[t].size;return e}function Iy(n,e){const t=new Set,s=[],r={};for(const a of e.names())t.add(a);const i=[],o=[];for(i.push(n);i.length>0;){const a=i[i.length-1];if(t.has(a.name)){i.pop();continue}const l=o[o.length-1]===i.length-1;if(a.inputs.length===0||l)i.pop(),s.push(a),t.add(a.name),l&&o.pop();else{o.push(i.length-1);for(const c of a.inputs)r[c.name]==null&&(r[c.name]=new Set),r[c.name].add(a.name),!t.has(c.name)&&i.push(c)}}return{sorted:s,recipientMap:r}}function K8(n){let e;if(n.sourceLayer.inboundNodes.length===1)e=n.sourceLayer.output;else{let t=null;for(let s=0;s100,H8);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function Av(n,e){return le(()=>As(lt(Z(n,n),e,!0)))}class dp extends Ku{getConfig(){return{}}}class h_ extends dp{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return le(()=>{const t=Av(e,this.axis),s=Mr(t,0,this.maxValue);return Z(e,ut(s,ke(Zn(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}h_.className="MaxNorm";we(h_);class d_ extends dp{constructor(e){super(),this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return le(()=>ut(e,ke(Zn(),Av(e,this.axis))))}getConfig(){return{axis:this.axis}}}d_.className="UnitNorm";we(d_);class p_ extends dp{apply(e){return $l(e)}}p_.className="NonNeg";we(p_);class f_ extends dp{constructor(e){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return le(()=>{const t=Av(e,this.axis),s=ke(Z(this.rate,Mr(t,this.minValue,this.maxValue)),Z(1-this.rate,t));return Z(e,ut(s,ke(Zn(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}f_.className="MinMaxNorm";we(f_);const Ey={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function ns(n){return vv(n)}function ky(n,e={}){return ap(n,Hr.getMap().classNameMap,e,"constraint")}function ss(n){if(n==null)return null;if(typeof n=="string"){const t={className:n in Ey?Ey[n]:n,config:{}};return ky(t)}else return n instanceof dp?n:ky(n)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */async function Da(n){if(n==null)return;const e=[],t=[],s=[];for(const r in n){const i=n[r];if(typeof i!="number"){const o=i;e.push(o.data()),t.push(r),s.push(o)}}if(e.length>0){const r=await Promise.all(e);for(let i=0;ike(this.totals[r],Z(i,s)));this.totals[r]=a,o?.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(const s of this.params.metrics)this.totals[s]!=null&&(typeof this.totals[s]=="number"?t[s]=this.totals[s]/this.seen:le(()=>{const r=Z(ut(1,this.seen),this.totals[s]);t[s]=r,this.totals[s].dispose(),er(t[s])}))}}class Q8 extends Vh{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(const s in t)this.history[s]==null&&(this.history[s]=[]),this.history[s].push(t[s])}async syncData(){const e=[],t=[],s=[];for(const i in this.history){const o=this.history[i];for(let a=0;anew eL(s,e))}class Gr{constructor(){}static registerCallbackConstructor(e,t){N(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),Gr.checkForDuplicate(t),Gr.constructors[e]==null&&(Gr.constructors[e]=[]),Gr.constructors[e].push(t)}static checkForDuplicate(e){for(const t in Gr.constructors)Gr.constructors[+t].forEach(r=>{if(r===e)throw new Y("Duplicate callback constructor.")})}static clear(){Gr.constructors={}}static createCallbacks(e){const t=[];for(const s in Gr.constructors){const r=+s;e>=r&&t.push(...Gr.constructors[r])}return t.map(s=>new s)}}Gr.constructors={};function x_(n,e,t,s,r,i,o,a,l){const c=new Q8,u=[new J8,...Gr.createCallbacks(e)];n!=null&&u.push(...n),u.push(c);const h=new Z8(u);return h.setParams({epochs:t,initialEpoch:s,samples:r,steps:i,batchSize:o,verbose:e,doValidation:a,metrics:l}),{callbackList:h,history:c}}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function To(n,e={},t=!1){return ap(n,Hr.getMap().classNameMap,e,"layer",t)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function Gf(n,e){return le(()=>{n.dtype!=="float32"&&(n=qe(n,"float32"));const t=lt(cp(n),e,!0),s=um(t.shape,Zn()),r=As(Ca(t,s));return ut(n,r)})}function zm(n,e){return le(()=>Xn(cp(ft(e,n)),-1))}function Rv(n,e){return le(()=>Xn(Ls(ft(e,n)),-1))}function Mv(n,e){return le(()=>{const t=ft(n,e),s=Mr(Ls(n),Zn(),Number.MAX_VALUE),r=Ls(ut(t,s));return Z(100,Xn(r,-1))})}function tL(n,e){return le(()=>{const t=Mr(e,Zn(),Number.MAX_VALUE),s=Zi(ke(1,t)),r=Mr(n,Zn(),Number.MAX_VALUE),i=Zi(ke(1,r));return Xn(cp(ft(s,i)),-1)})}function nL(n,e){return le(()=>{const t=Ca(0,ft(1,Z(n,e)));return Xn(cp(t),-1)})}function sL(n,e){return le(()=>{const t=Ca(0,ft(1,Z(n,e)));return Xn(t,-1)})}function rL(n,e){return le(()=>{const t=lt(Z(n,e),-1),s=wi(Z(ft(1,n),e),-1);return Ca(0,ke(1,ft(s,t)))})}function iL(n,e){return le(()=>{const t=Math.log(2),s=ft(e,n),r=ft(ke(s,tp(Z(-2,s))),t);return Xn(r,-1)})}function Wh(n,e,t=!1){return le(()=>{if(t)e=np(e);else{const s=lt(e,e.shape.length-1,!0);e=ut(e,s)}return e=Mr(e,Zn(),1-Zn()),Bn(lt(Z(qe(n,"float32"),Zi(e)),e.shape.length-1))})}function Hf(n,e,t=!1){return le(()=>{const s=qe(pm(T8(n)),"int32");e=Mr(e,Zn(),1-Zn());const r=e.shape,i=se(jC(s,r[r.length-1]),r);return Wh(i,e,t)})}function oL(n,e){if(!Wt(n.shape,e.shape))throw new Y(`logits and labels must have the same shape, but got shapes ${JSON.stringify(n.shape)} and ${JSON.stringify(e.shape)}`);return le(()=>{const t=$l(e),s=Bn(Ls(e));return ke(ft(t,Z(e,n)),qC(Yi(s)))})}function Bm(n,e){return le(()=>{let t;return t=Mr(e,Zn(),1-Zn()),t=Zi(ut(t,ft(1,t))),Xn(oL(n,t),-1)})}function aL(n,e){return le(()=>{const t=Mr(n,Zn(),1),s=Mr(e,Zn(),1);return lt(Z(n,Zi(ut(t,s))),-1)})}function lL(n,e){return le(()=>{const t=Zi(ke(Zn(),e));return Xn(ft(e,Z(n,t)),-1)})}function v_(n,e){return le(()=>{const t=Gf(n,-1),s=Gf(e,-1),r=Z(t,s);return Bn(lt(r,-1))})}const qf={meanSquaredError:zm,meanAbsoluteError:Rv,meanAbsolutePercentageError:Mv,meanSquaredLogarithmicError:tL,squaredHinge:nL,hinge:sL,categoricalHinge:rL,logcosh:iL,categoricalCrossentropy:Wh,sparseCategoricalCrossentropy:Hf,binaryCrossentropy:Bm,kullbackLeiblerDivergence:aL,poisson:lL,cosineProximity:v_};function Dg(n){if(typeof n=="string"){if(n in qf)return qf[n];let e=`Unknown loss ${n}`;throw n.toLowerCase().includes("softmaxcrossentropy")&&(e=`Unknown loss ${n}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new Y(e)}else return n}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function b_(n,e){return le(()=>{const t=Z(.5,ti(e)),s=Hi(Dr(e,t),n.dtype);return Xn(ji(n,s),-1)})}function y_(n,e){return le(()=>Hi(ji(Fh(n,-1),Fh(e,-1)),"float32"))}function cL(n,e){return le(()=>qe(lt(Ao(ji(n,1),ji(e,1))),"float32"))}function uL(n,e){return le(()=>qe(lt(Ao(ji(n,0),ji(e,1))),"float32"))}function hL(n,e){return le(()=>{const t=cL(n,e),s=uL(n,e),r=ke(t,s);return qe(zs(Dr(r,0),ut(t,r),0),"float32")})}function dL(n,e){return Bm(n,e)}function pL(n,e){return n.rank===e.rank&&(n=sp(n,[n.rank-1])),e=Fh(e,-1),e.dtype!==n.dtype&&(e=qe(e,n.dtype)),qe(ji(n,e),"float32")}const fL=zm,mL=zm,gL=Rv,xL=Rv,vL=Mv,bL=Mv,w_=Wh,yL=v_,S_=Hf,Xf={binaryAccuracy:b_,categoricalAccuracy:y_,precision:hL,categoricalCrossentropy:w_,sparseCategoricalCrossentropy:S_,mse:fL,MSE:mL,mae:gL,MAE:xL,mape:vL,MAPE:bL,cosine:yL};function wL(n){if(typeof n=="string"&&n in Xf)return Xf[n];if(typeof n!="string"&&n!=null)return n;throw new Y(`Unknown metric ${n}`)}function Pp(n){if(Li(n!==null,`Unknown LossOrMetricFn ${n}`),typeof n=="string")return n;{let e;for(const t of Object.keys(qf))if(qf[t]===n){e=t;break}if(e!==void 0)return e;for(const t of Object.keys(Xf))if(Xf[t]===n){e=t;break}return e!==void 0?e:n.name}}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function SL(n){const e={Adagrad:()=>Wa.adagrad(.01),Adadelta:()=>Wa.adadelta(1,.95,Zn()),Adam:()=>Wa.adam(.001,.9,.999,Zn()),Adamax:()=>Wa.adamax(.002,.9,.999,Zn(),0),RMSProp:()=>Wa.rmsprop(.001,.9,0,Zn()),SGD:()=>Wa.sgd(.01)};if(e.adagrad=e.Adagrad,e.adadelta=e.Adadelta,e.adam=e.Adam,e.adamax=e.Adamax,e.rmsprop=e.RMSProp,e.sgd=e.SGD,n in e)return e[n]();throw new Y(`Unknown Optimizer ${n}`)}/** + * @license + * Copyright 2019 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const Ry=1*1024*1024;function My(n,e,t=!1){if(n==null||typeof n!="object"||Object.getPrototypeOf(n)!==Object.prototype||!gx(n))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(t){const s=JSON.stringify(n);s.length>Ry&&console.warn(`User-defined metadata of model "${e}" is too large in size (length=${s.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${Ry}.`)}}function gx(n){if(n===null)return!0;if(typeof n=="object")if(Object.getPrototypeOf(n)===Object.prototype){const e=Object.keys(n);for(const t of e)if(typeof t!="string"||!gx(n[t]))return!1;return!0}else if(Array.isArray(n)){for(const e of n)if(!gx(e))return!1;return!0}else return!1;else{const e=typeof n;return e==="string"||e==="number"||e==="boolean"}}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function CL(n,e,t,s=console.log){const r=TL(n),i=["Layer (type)","Input Shape","Output shape","Param #"];r?(e=e||90,t=t||[.32,.61,.89,1]):(e=e||115,t=t||[.24,.48,.7,.8,1]),t[t.length-1]<=1&&(t=t.map(u=>Math.floor(e*u)));let o;if(!r){i.push("Receives inputs"),o=[];for(const u in n.nodesByDepth)o.push(...n.nodesByDepth[u])}s("_".repeat(e)),Kf(i,t,s),s("=".repeat(e));const a=n.layers;for(let u=0;u1||r.length===1&&r[0].inboundLayers.length>1){e=!1;break}s.push(...r)}if(e)for(const r of n.layers){let i=!1;for(const o of r.inboundNodes)if(s.indexOf(o)!==-1)if(i){e=!1;break}else i=!0;if(!e)break}return e}function Kf(n,e,t=console.log){let s="";for(let r=0;r0&&(s=s.slice(0,s.length-1)+" "),s+=n[r],s=s.slice(0,e[r]),s+=" ".repeat(e[r]-s.length);t(s)}function IL(n,e,t){let s,r;try{r=n.inboundNodes.map(l=>JSON.stringify(l.inputShapes)).join(",")}catch{r="multiple"}try{s=JSON.stringify(n.outputShape)}catch{s="multiple"}const i=n.name,o=n.getClassName(),a=[`${i} (${o})`,r,s,n.countParams().toString()];Kf(a,e,t)}function EL(n,e,t,s){let r,i;try{i=n.inboundNodes.map(h=>JSON.stringify(h.inputShapes)).join(",")}catch{i="multiple"}try{r=JSON.stringify(n.outputShape)}catch{r="multiple"}const o=[];for(const h of n.inboundNodes)if(!(t!=null&&t.length>0&&t.indexOf(h)===-1))for(let d=0;d{const e=Object.keys(n);if(e.length===0)return!1;const t=e[0].split("/");return!isNaN(parseInt(t[t.length-1],10))};class ci extends Ot{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,this.name==null){const v=this.getClassName().toLowerCase();this.name=Lm(v)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],ta(this.inputs).length!==this.inputs.length)throw new Y(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(v=>v.name)}`);ta(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(v=>v.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const v of this.outputs){const b=v.sourceLayer,y=v.nodeIndex,w=v.tensorIndex;this.outputLayers.push(b),this.outputLayersNodeIndices.push(y),this.outputLayersTensorIndices.push(w)}for(const v of this.inputs){const b=v.sourceLayer,y=v.nodeIndex,w=v.tensorIndex;Li(y===0,"input layer has >1 nodes"),Li(w===0,"input layer has >1 tensors"),this.inputLayers.push(b),this.inputLayersNodeIndices.push(y),this.inputLayersTensorIndices.push(w)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let v=0;vv.shape),this.internalOutputShapes=this.outputs.map(v=>v.shape);const t={},s={},r={},i={},o={},a=[],l=(v,b,y,w,C,T)=>{(w==null||C==null||T==null)&&(w=v.sourceLayer,C=v.nodeIndex,T=v.tensorIndex);const E=w.inboundNodes[C];if(y.indexOf(E)!==-1)throw new Yr(`The tensor ${v.name} at layer "${w.name}" is part of a cycle.`);if(b.indexOf(E)!==-1)return;this.containerNodes.add(ci.nodeKey(w,C)),w.id in o||(o[w.id]=Object.keys(o).length),y.indexOf(E)===-1&&y.push(E);const R=E.inboundLayers.length;for(let _=0;_=0;)y.splice(y.indexOf(E),1);a.push(E)},c=[],u=[];for(const v of this.outputs)l(v,c,u);const h=a.slice().reverse();for(const v of h){s[v.id]=v,v.id in t||(t[v.id]=0);let b=t[v.id];const y=r[v.outboundLayer.id]==null?0:r[v.outboundLayer.id];b=Math.max(b,y),r[v.outboundLayer.id]=b,i[v.outboundLayer.id]=v.outboundLayer,t[v.id]=b;for(let w=0;wparseInt(v,10)).sort(Np);this.layers=[];for(const v of f){const b=p[v];b.sort((y,w)=>{const C=o[y.id],T=o[w.id];return CT?1:0});for(const y of b)y instanceof ci&&this.internalContainerRefs.push(y),this.layers.push(y)}this.layersByDepth=p,f=Object.keys(d).map(v=>parseInt(v,10)).sort(Np);const x=this.inputs.slice(),m=[];for(const v of f)for(const b of d[v]){const y=b.outboundLayer;if(y!=null){for(const w of b.inputTensors)if(x.indexOf(w)===-1)throw new Yr(`Graph disconnected: cannot obtain value for tensor ${w} at layer "${y.name}". The following previous layers were accessed without issue: ${m}`);for(const w of b.outputTensors)x.push(w);m.push(y.name)}}this.nodesByDepth=d;const g=this.layers.map(v=>v.name);for(const v of g){const b=g.filter(y=>y===v).length;if(b!==1)throw new Yr(`The name "${v}" is used ${b} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new Om({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(v=>null),outputMasks:this.outputs.map(v=>null),inputShapes:this.inputs.map(v=>v.shape),outputShapes:this.outputs.map(v=>v.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(s=>s.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new Y("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const s of this.layers)t.push(...s.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const s={};let r=0;const i=kL(e);i&&this.parseWeights(e);for(const a of this.layers)for(const[l,c]of a.weights.entries()){const u=i?`${c.name.split("/").slice(0,-1).join("/")+"/"}${l}`:c.originalName;if(s[u]!=null)throw new Y(`Duplicate weight name: ${u}`);s[u]=c,r++}const o=[];for(const a in e){let l=a;if(s[a]==null){const c=a.split("/");l=c.slice(0,-2).concat([c[c.length-1]]).join("/")}if(s[l]!=null)o.push([s[l],e[a]]);else if(t)throw new Y(`Provided weight data has no target variable: ${a}`);delete s[l]}if(t){const a=[];for(const l in s)a.push(l);if(a.length>0)throw new Y(`${a.length} of ${r} weights are not set: ${a}`)}kv(o)}parseWeights(e){for(const t in Object.keys(e)){const s=t.split("/"),r=["vars","layer_checkpoint_dependencies"],i=s.map(o=>o.startsWith("_")?o.slice(1):o).filter(o=>!r.includes(o)).join("/");i!==t&&(e[i]=e[t],delete e[t])}}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${__}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const s=vx(this.updatedConfig());return t?JSON.stringify(s):s}call(e,t){return le(()=>{e=nn(e);const s=new jo;for(let r=0;r{e=nn(e);let s;return t==null?s=wl(null,e.length):s=nn(t),this.runInternalGraph(e,s)[1]})}computeOutputShape(e){const t=Bf(e);if(t.length!==this.inputLayers.length)throw new Y(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const s={};for(let a=0;aparseInt(a,10)).sort(Np);if(r.length>1)for(const a of r){const l=this.nodesByDepth[a];for(const c of l){const u=c.outboundLayer;if(this.inputLayers.map(x=>x.id).indexOf(u.id)!==-1)continue;const h=[];for(let x=0;xparseInt(l,10)).sort(Np);for(const l of r){const c=this.nodesByDepth[l];for(const u of c){const h=u.outboundLayer,d=u.inputTensors,p=u.outputTensors,f=new Array;for(const x of d)x.id in s&&f.push(s[x.id]);if(f.length===d.length){let x={},m,g,v,b;if(u.callArgs!=null&&(x=u.callArgs),f.length===1){const[y,w]=f[0];x.mask==null&&(x.mask=w),v=nn(h.call(y,x)),b=nn(h.computeMask(y,w)),m=[y],g=[w]}else m=f.map(y=>y[0]),g=f.map(y=>y[1]),x.mask==null&&(x.mask=g),v=nn(h.call(m,x)),b=nn(h.computeMask(m,g));if(h.activityRegularizer)throw new Mt("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let y=0;y{const e=[];for(const t of this.layers)for(let s=0;s0){const x=[];for(let m=0;m0&&m.apply(Ys(v),b)}function c(m){const g=m.name,v=To(m,t.customObjects!=null?t.customObjects:{});v.setFastWeightInitDuringBuild(r),i[g]=v,m.inboundNodes.forEach(y=>{if(!(y instanceof Array))throw new Y(`Corrupted configuration, expected array for nodeData: ${y}`);a(v,y)})}const u=t.name,h=t.layers;for(const m of h)c(m);for(;!d8(o);)for(const m of h){const g=i[m.name];if(g.name in o){const v=o[g.name];delete o[g.name];for(const b of v)l(g,b)}}const d=[],p=[],f=t.inputLayers;for(const m of f){const g=m[0],v=m[1],b=m[2];Li(g in i);const w=i[g].inboundNodes[v].outputTensors;d.push(w[b])}const x=t.outputLayers;for(const m of x){const g=m[0],v=m[1],b=m[2];Li(g in i);const w=i[g].inboundNodes[v].outputTensors;p.push(w[b])}return new e({inputs:d,outputs:p,name:u})}get stateful(){if(this._stateful)throw new Y("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){le(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function AL(n,e,t){const s=e.length;if(n==null||Array.isArray(n)&&n.length===0)return e.map(r=>null);if(s===1)return Array.isArray(n)&&n.length===1?n:typeof n=="object"&&e[0]in n?[n[e[0]]]:[n];if(Array.isArray(n)){if(n.length!==s)throw new Error(`Provided ${t} is an array of ${n.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return n}else if(typeof n=="object"&&Object.keys(n).length>0&&typeof n[Object.keys(n)[0]]=="object"){const r=[];return e.forEach(i=>{i in n?r.push(n[i]):r.push(null)}),r}else throw new Error(`The model has multiple (${s}) outputs, so ${t} must be either an array with ${s} elements or an object with ${e} keys. Provided ${t} not understood: ${JSON.stringify(n)}`)}function T_(n,e){return AL(n,e,"classWeight")}async function I_(n,e,t,s){if(t!=null){const r=le(()=>{if(n.shape.length===1)return il(n);if(n.shape.length===2){if(n.shape[1]>1)return Fh(n,1);if(n.shape[1]===1)return se(n,[n.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${n.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${n.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),i=Array.from(await r.data());Nt(r);const o=[];return i.forEach(a=>{if(t[a]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${a} exists in the data but not in classWeight`);o.push(t[a])}),Zs(o,"float32")}else return null}function RL(n,e){return Z(n,e)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const ML=32;function E_(n,e){let t,s;const r=e;t=r.xs,s=r.ys,N(t!=null&&s!=null,()=>`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 ${e}`);const i=Ny("input",n.inputNames,t),o=Ny("output",n.outputNames,s),a=i[0].shape[0];N(i.length===n.inputs.length,()=>`LayersModel has ${n.inputs.length} inputs, but the dataset provides ${i.length} inputs. (Expected input keys: ${JSON.stringify(n.inputNames)})`),N(o.length===n.outputs.length,()=>`LayersModel has ${n.outputs.length} outputs, but the dataset provides ${o.length} outputs. (Expected output keys: ${JSON.stringify(n.outputNames)})`);for(let l=0;l`Batch size mismatch: input ${n.inputNames[l]} has ${i[l].shape[0]}; expected ${a} based on input ${n.inputNames[0]}.`);for(let l=0;l`Batch size mismatch: output ${n.outputNames[l]} has ${o[l].shape[0]}; expected ${a} based on input ${n.inputNames[0]}.`);return{xs:i,ys:o}}function Ny(n,e,t){if(t instanceof Yn)return[t];if(Array.isArray(t))return N(t.length===e.length,()=>`Received an array of ${t.length} Tensors, but expected ${e.length} to match the ${n} keys ${e}.`),t;{const s=[];for(const r of e){if(t[r]==null)throw new Y(`The feature data generated by the dataset lacks the required ${n} key '${r}'.`);s.push(t[r])}return s}}function NL(n){if(n.length===3)throw new Mt("Validation with sample weights is not implemented yet.");return{xs:n[0],ys:n[1]}}async function $L(n,e,t){const s=t.batchesPerEpoch!=null;if(N(n.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),N(t!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),N(t.epochs!=null&&t.epochs>0&&Number.isInteger(t.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${t.epochs}`),N(!s||t.batchesPerEpoch>0&&Number.isInteger(t.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${t.batchesPerEpoch}`),N(t.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),n.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");n.isTraining=!0;try{const r=t.validationData!=null;let i,o;if(r)if($y(t.validationData))N(t.validationBatches==null||t.validationBatches>0&&Number.isInteger(t.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${t.validationBatches}`);else{const m=NL(t.validationData);i=m.xs,o=m.ys}const a=n.makeTrainFunction(),l=n.getDedupedMetricsNames();let c;r?c=l.slice().concat(l.map(m=>"val_"+m)):c=l.slice();const u=g_(t.callbacks,t.yieldEvery),h=t.verbose==null?1:t.verbose,{callbackList:d,history:p}=x_(u,h,t.epochs,null,null,DL(e,t),null,r,c);d.setModel(n),n.history=p,await d.onTrainBegin(),n.stopTraining_=!1;let f=t.initialEpoch==null?0:t.initialEpoch,x=await e.iterator();for(;f=t.batchesPerEpoch:b.done){if(r){let y;$y(t.validationData)?y=nn(await n.evaluateDataset(t.validationData,{batches:t.validationBatches})):y=nn(n.evaluate(i,o,{batchSize:t.validationBatchSize==null?ML:t.validationBatchSize,verbose:0}));for(let w=0;w0)throw new Mt("Verbose mode is not implemented yet.");N(!s||t.batches>0&&Number.isInteger(t.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(t.batches)}`);const o=PL(e)?e:await e.iterator();let a=0,l=0;for(;!s||l{if(c.value){const{xs:u,ys:h}=E_(n,c.value),d=u.concat(h),p=le(()=>r(d));if(Nt(d),l===0)for(let x=0;xke(i[x],Z(f,m))),l>0&&Nt(g)}Nt(p),a+=f,++l}return i}),c.done){s&&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, ${t.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let c=0;c0&&Number.isInteger(n),()=>`batchSize is required to be a positive integer, but got ${n}`)}function mh(n,e,t){return n==null?[null]:Array.isArray(n)?n.map(s=>al(s,e,t-e)):al(n,e,t-e)}function bx(n,e){return le(()=>n==null?null:Array.isArray(n)?n.map(t=>bx(t,e)):t_(n,e.dtype==="int32"?e:qe(e,"int32")))}function Lg(n,e){const t=[];let s=0,r=null;for(;s=n&&(r=n),t.push([s,r]),s=r;return t}function k_(n){const e=[];n instanceof Yn&&(n=[n]);for(let t=0;tt.push(r.id));else if(e!=null)for(const r in e){const i=e[r];t.push(i.id)}const s=[];if(n instanceof Yn)t.indexOf(n.id)===-1&&s.push(n);else if(Array.isArray(n))n.forEach(r=>{t.indexOf(r.id)===-1&&s.push(r)});else if(n!=null)for(const r in n){const i=n[r];t.indexOf(i.id)===-1&&s.push(i)}s.forEach(r=>{r.isDisposed||r.dispose()})}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function FL(n){return n instanceof Yn}function yx(n){return Array.isArray(n)}function Dy(n){return!FL(n)&&!yx(n)}function Py(n,e,t,s=!0,r=""){if(e==null||e.length===0){if(n!=null){let o=!1;if(yx(n)&&n.length>0)o=!0;else if(Dy(n)){for(const a in n)if(n.hasOwnProperty(a)){o=!0;break}}else o=!0;if(o)throw new Y(`Error when checking model ${r} expected no data, but got ${n}`)}return[]}if(n==null)return e.map(o=>null);let i;if(Dy(n)){n=n,i=[];for(const o of e){if(n[o]==null)throw new Y(`No data provided for "${o}". Need data for each key in: ${e}`);i.push(n[o])}}else if(yx(n)){if(n=n,n.length!==e.length)throw new Y(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${e.length} Tensor(s), but instead got the following list of Tensor(s): ${n}`);i=n}else{if(n=n,e.length>1)throw new Y(`The model ${r} expects ${e.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${n.shape}`);i=[n]}if(i=k_(i),t!=null)for(let o=0;o=0&&c!==u)throw new Y(`${r} expected a batch of elements where each example has shape [${t[o].slice(1,t[o].length)}] (i.e.,tensor shape [*,${t[o].slice(1,t[o].length)}]) but the ${r} received an input with ${a.shape[0]} examples, each with shape [${a.shape.slice(1,a.shape.length)}] (tensor shape [${a.shape}])`)}}return i}function OL(n,e,t){const s=ta(n.map(i=>i.shape[0]));s.sort();const r=ta(e.map(i=>i.shape[0]));if(r.sort(),s.length>1)throw new Y(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(n.map(i=>i.shape))}`);if(r.length>1)throw new Y(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(i=>i.shape))}`);if(s.length>0&&r.length>0&&!Wt(s,r))throw new Y(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${r[0]} target sample(s).`)}function zL(n,e,t){const s=[zm,Bm,Wh];for(let r=0;r1)throw new Y(`The model expects ${e.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(n.shape)}.`);i=[n]}if(t!=null)for(let o=0;o[]);let t;if(typeof n=="string"||typeof n=="function")t=[n];else if(Array.isArray(n)||typeof n=="object")t=n;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${n}`);if(Array.isArray(t))return e.map(s=>t);{const s=[];for(const r of e){let i=t.hasOwnProperty(r)?t[r]:[];Array.isArray(i)||(i=[i]),s.push(i)}return s}}const UL="layers-model";class Sc extends ci{constructor(e){super(e),this.isTraining=!1}summary(e,t,s=console.log){if(!this.built)throw new Y("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).");CL(this,e,t,s)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=SL(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Ta))throw new Y("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(const o in e.loss)if(this.outputNames.indexOf(o)===-1)throw new Y(`Unknown entry in loss dictionary: "${o}". Only expected the following keys: ${this.outputNames}`);for(const o of this.outputNames)e.loss[o]==null&&console.warn(`Output "${o}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${o} during training`),t.push(Dg(e.loss[o]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new Y(`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}.`);t=e.loss.map(a=>Dg(a))}else{const o=Dg(e.loss);this.outputs.forEach(a=>{t.push(o)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let o=0;o{for(let o=0;o1&&(this.metricsTensors.push([a,o]),this.metricsNames.push(this.outputNames[o]+"_loss"))}});const r=BL(e.metrics,this.outputNames),i=(o,a,l)=>{this.outputNames.length>1&&(a=this.outputNames[o]+"_"+a),this.metricsNames.push(a),this.metricsTensors.push([l,o])};ol("metric",()=>{for(let o=0;o{const u="";let h,d,p;for(const f of c){if(typeof f=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(f)!==-1){const m=this.internalOutputShapes[o];m[m.length-1]===1||this.lossFunctions[o]===Bm?["accuracy","acc"].indexOf(f)!==-1?d=b_:["crossentropy","ce"].indexOf(f)!==-1&&(d=dL):this.lossFunctions[o]===Hf?["accuracy","acc"].indexOf(f)!==-1?d=pL:["crossentropy","ce"].indexOf(f)!==-1&&(d=S_):["accuracy","acc"].indexOf(f)!==-1?d=y_:["crossentropy","ce"].indexOf(f)!==-1&&(d=w_);let g;["accuracy","acc"].indexOf(f)!==-1?g="acc":["crossentropy","ce"].indexOf(f)!==-1&&(g="ce"),p=d,h=u+g}else p=wL(f),h=u+Pp(f);let x;ol(h,()=>{x=p}),i(o,h,x)}})(a)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&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,s={}){const r=s.batchSize==null?32:s.batchSize;Pg(r);const o=this.standardizeUserDataXY(e,t,!0,r);try{const a=o[0].concat(o[1]);this.makeTestFunction();const l=this.testFunction,c=this.testLoop(l,a,r,s.verbose,s.steps);return Ys(c)}finally{ii(o[0],e),ii(o[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),LL(this,e,t)}checkNumSamples(e,t,s,r="steps"){let i;if(s!=null){if(i=null,t!=null)throw new Y(`If ${r} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?i=e[0].shape[0]:i=e.shape[0];else throw new Y(`Either the input data should have a defined shape, or ${r} shoud be specified.`);return i}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new Y("`outputs` is an empty Array, which is not allowed.");const s=Array.isArray(t),r=s?t:[t],i=this.retrieveSymbolicTensors(r),o=new jo;if(e instanceof Yn&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new Y(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let l=0;la.name);for(let a=0;a0){const r=[];throw t.forEach((i,o)=>{i==null&&r.push(e[o])}),new Y(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(r)}`)}return t}predictLoop(e,t=32,s=!1){return le(()=>{const r=this.checkNumSamples(e);if(s)throw new Mt("Verbose predictLoop() is not implemented yet.");const i=Lg(r,t),o=this.outputs.map(a=>[]);for(let a=0;a{const c=i[a][0],u=i[a][1],h=mh(e,c,u),d=[];if(Array.isArray(h))for(let f=0;fo[u].push(c));return Ys(o.map(a=>tr(a,0)))})}predict(e,t={}){const s=k_(e);Ly(s,this.inputNames,this.feedInputShapes,!1);try{const r=t.batchSize==null?32:t.batchSize;return Pg(r),this.predictLoop(s,r)}finally{ii(s,e)}}predictOnBatch(e){Ly(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,s=!0,r){if(this.optimizer_==null)throw new Yr("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const i=[];for(let o=0;o0&&e[0].shape[0]%r!==0)throw new Y(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${r}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,s,r,i=!0,o){const[a,l]=this.standardizeUserDataXY(e,t,i,o);if(s!=null)throw new Error("sample weight is not supported yet.");let c=null;if(r!=null){const u=T_(r,this.outputNames);c=[];for(let h=0;h{const o=this.checkNumSamples(t,s,i,"steps"),a=[];if(r>0)throw new Mt("Verbose mode is not implemented yet.");if(i!=null)throw new Mt("steps mode in testLoop() is not implemented yet");{const l=Lg(o,s),c=Zs(Ii(0,o));for(let u=0;u1){const o=yy(e.slice(0,s),r);i+=`_${o}`}t.push(i)}return t}makeTrainFunction(){return e=>{const t=[],s=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),i=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),o=[],a=()=>{const h=[];for(let x=0;x1&&x{f=ke(f,x)}),f},l=this.collectedTrainableWeights.map(h=>h.read());return[this.optimizer_.minimize(a,!0,l)].concat(o)}}makeTestFunction(){this.testFunction=e=>le(()=>{const t=[];let s;const r=e.slice(0,this.inputs.length),i=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),o=[];for(let c=0;c0){if(m=!0,s.validationData.length===2)l=s.validationData[0],c=s.validationData[1];else throw s.validationData.length===3?new Mt("validationData including sample weights is not supported yet."):new Y(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);const _=await this.standardizeUserData(l,c,null,null,!0,p);u=_[0],h=_[1],g=u.concat(h)}else if(s.validationSplit!=null&&s.validationSplit>0&&s.validationSplit<1){m=!0;const R=Math.floor(r[0].shape[0]*(1-s.validationSplit)),_=r[0].shape[0];u=mh(r,R,_),o=r,r=mh(r,0,R),h=mh(i,R,_),a=i,i=mh(i,0,R),g=u.concat(h)}else s.validationSteps!=null&&(m=!0);const v=r.concat(i).concat(d);this.checkTrainableWeightsConsistency();const b=this.makeTrainFunction(),y=this.getDedupedMetricsNames();let w,C;m?(this.makeTestFunction(),w=this.testFunction,C=y.slice().concat(y.map(R=>"val_"+R))):(w=null,g=[],C=y.slice());const T=g_(s.callbacks,s.yieldEvery);return await this.fitLoop(b,v,y,p,s.epochs,s.verbose,T,w,g,s.shuffle,C,s.initialEpoch,null,null)}finally{this.isTraining=!1,ii(r,e),ii(i,t),ii(o,e),ii(a,t),ii(u,l),ii(h,c),d!=null&&Nt(d)}}async fitLoop(e,t,s,r,i,o,a,l,c,u,h,d,p,f){r==null&&(r=32),i==null&&(i=1),u==null&&(u=!0),d==null&&(d=0);let x=!1;if(l!=null&&c!=null&&(x=!0),f!=null&&(x=!0,p==null))throw new Y("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const m=this.checkNumSamples(t,r,p,"steps_per_epoch");let g;m!=null&&(g=Ii(0,m)),o==null&&(o=1);const{callbackList:v,history:b}=x_(a,o,i,d,m,p,r,x,h);v.setModel(this),this.history=b,await v.onTrainBegin(),this.stopTraining_=!1;for(let y=d;y{const _=T[E][0],k=T[E][1],F=al(C,_,k-_);R.batch=E,R.size=k-_;const B=bx(t,F),M=e(B);for(let P=0;Pxo(t))}else{const t=Object.keys(this.loss);e={};const s=this.loss;for(const r of t)if(typeof s[r]=="string")e[r]=xo(s[r]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[xo(Pp(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>xo(Pp(e)));{const e={};for(const t in this.metrics)e[t]=xo(Pp(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(e.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(e.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(e.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");const t=xx(e.optimizer_config),s=To(t);let r;if(typeof e.loss=="string")r=Ka(e.loss);else if(Array.isArray(e.loss))r=e.loss.map(o=>Ka(o));else if(e.loss!=null){r={};for(const o in e.loss)r[o]=Ka(e.loss[o])}let i;if(Array.isArray(e.metrics))i=e.metrics.map(o=>Ka(o));else if(e.metrics!=null){i={};for(const o in e.metrics)i[o]=Ka(e.metrics[o])}this.compile({loss:r,metrics:i,optimizer:s})}async save(e,t){if(typeof e=="string"){const c=mM(e);if(c.length===0)throw new Y(`Cannot find any save handlers for URL '${e}'`);if(c.length>1)throw new Y(`Found more than one (${c.length}) save handlers for URL '${e}'`);e=c[0]}if(e.save==null)throw new Y("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const s=await ey(this.getNamedWeights(t)),a={modelTopology:this.toJSON(null,!1),format:UL,generatedBy:`TensorFlow.js tfjs-layers v${__}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){a.trainingConfig=this.getTrainingConfig();const c="optimizer",{data:u,specs:h}=await ey(await this.optimizer.getWeights(),c);s.specs.push(...h),s.data=dM([s.data,u])}return this.userDefinedMetadata!=null&&(My(this.userDefinedMetadata,this.name,!0),a.userDefinedMetadata=this.userDefinedMetadata),a.weightData=s.data,a.weightSpecs=s.specs,e.save(a)}setUserDefinedMetadata(e){My(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}Sc.className="Model";we(Sc);class A_ extends Sc{}A_.className="Functional";we(A_);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Gh extends Sc{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:Lm("sequential_"),e.layers!=null)for(const t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(s=>s<0))throw new Y(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof Gh||e instanceof Sc;let s;if(t){if(s=e,s.outputs.length!==1)throw new Y("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(s.inputs.length!==1)throw new Y("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(e.inboundNodes.length===0){if(e.batchInputShape==null)throw new Y("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const r=W8({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(r)}if(t)this.outputs=s.outputs,this.inputs=s.inputs;else{if(e.inboundNodes.length!==1)throw new Y(`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(e.inboundNodes[0].outputTensors.length!==1)throw new Y("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=u_(this.outputs[0])}this.inboundNodes=[],new Om({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:wl(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(r=>r.shape),outputShapes:this.outputs[0].shape})}else{const r=e.apply(this.outputs[0]);if(Array.isArray(r))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=[r],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)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 this.model==null&&this.build(),this.model.call(e,t)}build(e){if(Yt(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new Sc({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,s=console.log){this.built||this.build(),super.summary(e,t,s)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,s={}){if(!this.built)throw new Yr("The model needs to be compiled before being used.");return this.model.evaluate(e,t,s)}async evaluateDataset(e,t){if(!this.built)throw new Yr("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&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 this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,s={}){if(!this.built)throw new Yr("The model needs to be compiled before being used.");return this.model.fit(e,t,s)}async fitDataset(e,t){if(!this.built)throw new Yr("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,s={},r=!1){let i,o={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new Y("Legacy serialization format not supported yet.");i=t}else N(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),i=t.layers,delete t.layers,o=t;const a=new e(o);if(!(a instanceof Gh))throw new Mt(`Sequential.fromConfig called on non-Sequential input: ${a}`);for(const l of i){const u=To(l,void 0,r);r&&u.setFastWeightInitDuringBuild(!0),a.add(u)}return a}set stopTraining(e){if(this.model==null)throw new Y("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(this.model==null)throw new Y("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 s={};s.className=t.getClassName(),s.config=t.getConfig(),e.push(s)}return{name:this.name,layers:e}}}Gh.className="Sequential";we(Gh);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */let Ms=class extends Ku{getConfig(){return{}}};class R_ extends Ms{apply(e,t=1){return E8(e,t)}}R_.className="elu";we(R_);class M_ extends Ms{apply(e){return t4(e)}}M_.className="selu";we(M_);class N_ extends Ms{apply(e){return $l(e)}}N_.className="relu";we(N_);class $_ extends Ms{apply(e){return le(()=>Bh(6,$l(e)))}}$_.className="relu6";we($_);class D_ extends Ms{apply(e){return e}}D_.className="linear";we(D_);class P_ extends Ms{apply(e){return Hu(e)}}P_.className="sigmoid";we(P_);class L_ extends Ms{apply(e){return A8(e)}}L_.className="hardSigmoid";we(L_);class F_ extends Ms{apply(e){return tp(e)}}F_.className="softplus";we(F_);class O_ extends Ms{apply(e){return k8(e)}}O_.className="softsign";we(O_);class z_ extends Ms{apply(e){return Nc(e)}}z_.className="tanh";we(z_);let Nv=class extends Ms{apply(e,t=-1){return np(e,t)}};Nv.className="softmax";we(Nv);class B_ extends Ms{apply(e,t=-1){return fm(e,t)}}B_.className="logSoftmax";we(B_);class U_ extends Ms{apply(e){return le(()=>le(()=>{const t=Math.sqrt(2),s=Z(.5,ke(1,VC(ut(e,t))));return Z(e,s)}))}}U_.className="gelu";we(U_);class V_ extends Ms{apply(e){return le(()=>Z(.5,Z(e,ke(1,Nc(Z(As(ut(2,Math.PI)),ke(e,Z(.044715,xl(e,3)))))))))}}V_.className="gelu_new";we(V_);class W_ extends Ms{apply(e){return le(()=>Z(e,Nc(tp(e))))}}W_.className="mish";we(W_);class G_ extends Ms{apply(e,t=1){return le(()=>Z(Hu(Z(e,t)),e))}}G_.className="swish";we(G_);function ca(n){return n.getClassName()}function Fg(n,e={}){return ap(n,Hr.getMap().classNameMap,e,"activation")}function ua(n){if(n==null){const e={};return e.className="linear",e.config={},Fg(e)}if(typeof n=="string"){const e={};return e.className=n,e.config={},Fg(e)}else return n instanceof Ms?n:Fg(n)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function VL(n){if(n!=null&&typeof n!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${n}`)}class H_ extends Ku{}class q_ extends H_{constructor(e){super(),VL(e),this.l1=e==null||e.l1==null?.01:e.l1,this.l2=e==null||e.l2==null?.01:e.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(e){return le(()=>{let t=On([1]);return this.hasL1&&(t=ke(t,lt(Z(this.l1,Ls(e))))),this.hasL2&&(t=ke(t,lt(Z(this.l2,cp(e))))),se(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}q_.className="L1L2";we(q_);const Fy={l1l2:"L1L2"};function hn(n){return vv(n)}function Oy(n,e={}){return ap(n,Hr.getMap().classNameMap,e,"regularizer")}function En(n){if(n==null)return null;if(typeof n=="string"){const t={className:n in Fy?Fy[n]:n,config:{}};return Oy(t)}else return n instanceof H_?n:Oy(n)}/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class X_ extends Ot{constructor(e){super(e??{}),this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=yt(e);let s=$l(e);return this.maxValue!=null&&(s=Mr(s,0,this.maxValue)),s}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}X_.className="ReLU";we(X_);class K_ extends Ot{constructor(e){super(e??{}),this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){const s=yt(e);return B2(s,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}K_.className="LeakyReLU";we(K_);class j_ extends Ot{constructor(e){if(super(e??{}),this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=In(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=En(e.alphaRegularizer),this.alphaConstraint=ss(e.alphaConstraint),e.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else if(typeof e.sharedAxes=="number")this.sharedAxes=[e.sharedAxes];else throw new Y(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=Yt(e);const t=e.slice(1);if(this.sharedAxes!=null)for(const r of this.sharedAxes)t[r-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const s={};if(this.sharedAxes!=null)for(let r=1;r{let s=yt(e);const r=t.mask;if(r!=null){const i=Z(ft(_a(s.shape),qe(r,s.dtype)),Ht(-1e9));s=ke(s,i)}return this.axis instanceof Array?this.axis.length>1?Yi(ft(s,XC(s,this.axis,!0))):this.softmax(s,this.axis[0]):this.softmax(s,this.axis)})}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}J_.className="Softmax";we(J_);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function Cc(n,e,t){if(typeof n=="number")return wl(n,e);if(n.length!==e)throw new Y(`The ${t} argument must be an integer or tuple of ${e} integers. Received: ${n.length} elements.`);for(let s=0;s(Gn(e),e==="channelsFirst"?qt(n,[0,2,3,1]):n))}function Q_(n,e){return le(()=>(Gn(e),e==="channelsFirst"?qt(n,[0,2,3,4,1]):n))}function WL(n,e,t,s=1,r="valid",i,o=1){return le(()=>{if(i==null&&(i=Ei()),Gn(i),n.shape.length!==3)throw new Y(`The input of a conv1dWithBias operation should be 3, but is ${n.shape.length} instead.`);if(e.shape.length!==3)throw new Y(`The kernel for a conv1dWithBias operation should be 3, but is ${e.shape.length} instead`);if(t!=null&&t.shape.length!==1)throw new Y(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(i==="channelsFirst"&&(n=qt(n,[0,2,1])),r==="causal")throw new Mt("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let a=FC(n,e,s,r==="same"?"same":"valid","NWC",o);return t!=null&&(a=Mi(a,t)),a})}function zy(n,e,t,s=[1,1],r="valid",i,o,a=null){return le(()=>{if(i==null&&(i=Ei()),Gn(i),n.rank!==3&&n.rank!==4)throw new Y(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${n.rank}.`);if(e.rank!==3&&e.rank!==4)throw new Y(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${n.rank}.`);let l=$v(n,i);if(r==="causal")throw new Mt("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=G$({x:l,filter:e,strides:s,pad:r==="same"?"same":"valid",dilations:o,dataFormat:"NHWC",bias:t,activation:a}),i==="channelsFirst"&&(l=qt(l,[0,3,1,2])),l})}function GL(n,e,t,s=[1,1,1],r="valid",i,o){return le(()=>{if(i==null&&(i=Ei()),Gn(i),n.rank!==4&&n.rank!==5)throw new Y(`conv3dWithBias expects input to be of rank 4 or 5, but received ${n.rank}.`);if(e.rank!==4&&e.rank!==5)throw new Y(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${n.rank}.`);let a=Q_(n,i);if(r==="causal")throw new Mt("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return a=HN(a,e,s,r==="same"?"same":"valid","NDHWC",o),t!=null&&(a=Mi(a,t)),i==="channelsFirst"&&(a=qt(a,[0,4,1,2,3])),a})}class Um extends Ot{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Um.verifyArgs(t),this.rank=e,us(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Mt(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Cc(t.kernelSize,e,"kernelSize"),this.strides=Cc(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Pr(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Gn(this.dataFormat),this.activation=ua(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=In(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=ss(t.biasConstraint),this.biasRegularizer=En(t.biasRegularizer),this.activityRegularizer=En(t.activityRegularizer),this.dilationRate=Cc(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new Y(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new Y(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new Y(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Li("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!bv(e.kernelSize,"number",1,3))throw new Y(`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:ca(this.activation),useBias:this.useBias,biasInitializer:An(this.biasInitializer),biasRegularizer:hn(this.biasRegularizer),activityRegularizer:hn(this.activityRegularizer),biasConstraint:ns(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class ju extends Um{constructor(e,t){super(e,t),this.kernel=null,ju.verifyArgs(t),this.filters=t.filters,us(this.filters,"filters"),this.kernelInitializer=In(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=ss(t.kernelConstraint),this.kernelRegularizer=En(t.kernelRegularizer)}build(e){e=Yt(e);const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new Y(`The channel dimension of the input should be defined. Found ${e[t]}`);const s=e[t],r=this.kernelSize.concat([s,this.filters]);this.kernel=this.addWeight("kernel",r,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]:s}}],this.built=!0}call(e,t){return le(()=>{e=yt(e);let s;const r=this.bias==null?null:this.bias.read(),i=j4(this.activation.getClassName());if(i!=null&&this.rank===2)s=zy(e,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate,i);else{if(this.rank===1)s=WL(e,this.kernel.read(),r,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)s=zy(e,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)s=GL(e,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Mt("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(s=this.activation.apply(s))}return s})}computeOutputShape(e){e=Yt(e);const t=[],s=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let i=0;i 0 but got ${JSON.stringify(e.filters)}`)}}class pp extends ju{constructor(e){super(2,e),pp.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!bv(e.kernelSize,"number",1,2))throw new Y(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}pp.className="Conv2D";we(pp);class fp extends ju{constructor(e){super(3,e),fp.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new Y(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}fp.className="Conv3D";we(fp);class eT extends pp{constructor(e){if(super(e),this.inputSpec=[new Jn({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new Y(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Yt(e),e.length!==4)throw new Y("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new Y("The channel dimension of the inputs should be defined. Found `None`.");const s=e[t],r=this.kernelSize.concat([this.filters,s]);this.kernel=this.addWeight("kernel",r,"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 Jn({ndim:4,axes:{[t]:s}})],this.built=!0}call(e,t){return le(()=>{let s=yt(e);if(s.shape.length!==4)throw new Y(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${s.shape.length}`);const r=s.shape,i=r[0];let o,a;this.dataFormat==="channelsFirst"?(o=2,a=3):(o=1,a=2);const l=r[o],c=r[a],u=this.kernelSize[0],h=this.kernelSize[1],d=this.strides[0],p=this.strides[1],f=Fi(l,d,u,this.padding),x=Fi(c,p,h,this.padding),m=[i,f,x,this.filters];this.dataFormat!=="channelsLast"&&(s=qt(s,[0,2,3,1]));let g=OC(s,this.kernel.read(),m,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=qt(g,[0,3,1,2])),this.bias!=null&&(g=Mi(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=Yt(e);const t=e.slice();let s,r,i;this.dataFormat==="channelsFirst"?(s=1,r=2,i=3):(s=3,r=1,i=2);const o=this.kernelSize[0],a=this.kernelSize[1],l=this.strides[0],c=this.strides[1];return t[s]=this.filters,t[r]=Fi(t[r],l,o,this.padding),t[i]=Fi(t[i],c,a,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}eT.className="Conv2DTranspose";we(eT);class tT extends fp{constructor(e){if(super(e),this.inputSpec=[new Jn({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new Y(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Yt(e),e.length!==5)throw new Y("Input should have rank 5; Received input shape: "+JSON.stringify(e));const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new Y("The channel dimension of the inputs should be defined. Found `None`.");const s=e[t],r=this.kernelSize.concat([this.filters,s]);this.kernel=this.addWeight("kernel",r,"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 Jn({ndim:5,axes:{[t]:s}})],this.built=!0}call(e,t){return le(()=>{let s=yt(e);if(s.shape.length!==5)throw new Y(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${s.shape.length}`);const r=s.shape,i=r[0];let o,a,l;this.dataFormat==="channelsFirst"?(l=2,o=3,a=4):(l=1,o=2,a=3);const c=r[l],u=r[o],h=r[a],d=this.kernelSize[0],p=this.kernelSize[1],f=this.kernelSize[2],x=this.strides[0],m=this.strides[1],g=this.strides[2],v=Fi(c,x,d,this.padding),b=Fi(u,m,p,this.padding),y=Fi(h,g,f,this.padding),w=[i,v,b,y,this.filters];this.dataFormat!=="channelsLast"&&(s=qt(s,[0,2,3,4,1]));let C=KN(s,this.kernel.read(),w,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(C=qt(C,[0,4,1,2,3])),this.bias!==null&&(C=Mi(C,this.bias.read(),this.dataFormat)),this.activation!==null&&(C=this.activation.apply(C)),C})}computeOutputShape(e){e=Yt(e);const t=e.slice();let s,r,i,o;this.dataFormat==="channelsFirst"?(s=1,r=2,i=3,o=4):(s=4,r=1,i=2,o=3);const a=this.kernelSize[0],l=this.kernelSize[1],c=this.kernelSize[2],u=this.strides[0],h=this.strides[1],d=this.strides[2];return t[s]=this.filters,t[r]=Fi(t[r],u,a,this.padding),t[i]=Fi(t[i],h,l,this.padding),t[o]=Fi(t[o],d,c,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}tT.className="Conv3DTranspose";we(tT);class nT extends ju{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new Y("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new Y("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(t.padding!=null&&t.padding!=="same"&&t.padding!=="valid")throw new Y(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=In(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=En(t.depthwiseRegularizer),this.depthwiseConstraint=ss(t.depthwiseConstraint),this.pointwiseInitializer=In(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=En(t.pointwiseRegularizer),this.pointwiseConstraint=ss(t.pointwiseConstraint)}build(e){if(e=Yt(e),e.length{e=yt(e);let s;if(this.rank===1)throw new Mt("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=qt(e,[0,2,3,1])),s=n4(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(s=Mi(s,this.bias.read(),this.dataFormat)),this.activation!=null&&(s=this.activation.apply(s)),this.dataFormat==="channelsFirst"&&(s=qt(s,[0,3,1,2])),s})}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=An(this.depthwiseInitializer),e.pointwiseInitializer=An(this.pointwiseInitializer),e.depthwiseRegularizer=hn(this.depthwiseRegularizer),e.pointwiseRegularizer=hn(this.pointwiseRegularizer),e.depthwiseConstraint=ns(this.depthwiseConstraint),e.pointwiseConstraint=ns(this.pointwiseConstraint),e}}nT.className="SeparableConv";class sT extends nT{constructor(e){super(2,e)}}sT.className="SeparableConv2D";we(sT);class Vm extends ju{constructor(e){super(1,e),Vm.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!bv(e.kernelSize,"number",1,1))throw new Y(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}Vm.className="Conv1D";we(Vm);class rT extends Ot{constructor(e){super(e),typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[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 le(()=>{if(e=yt(e),this.dataFormat==="channelsLast"){const s=Dp(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Dp(s,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{const s=Dp(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Dp(s,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}}rT.className="Cropping2D";we(rT);class iT extends Ot{constructor(e){super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Gn(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,y8(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){const t=e[2]==null?null:this.size[0]*e[2],s=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,s]}else{const t=e[1]==null?null:this.size[0]*e[1],s=e[2]==null?null:this.size[1]*e[2];return[e[0],t,s,e[3]]}}call(e,t){return le(()=>{let s=yt(e);const r=s.shape;if(this.dataFormat==="channelsFirst"){s=qt(s,[0,2,3,1]);const i=this.size[0]*r[2],o=this.size[1]*r[3],a=this.interpolation==="nearest"?So.resizeNearestNeighbor(s,[i,o]):So.resizeBilinear(s,[i,o]);return qt(a,[0,3,1,2])}else{const i=this.size[0]*r[1],o=this.size[1]*r[2];return this.interpolation==="nearest"?So.resizeNearestNeighbor(s,[i,o]):So.resizeBilinear(s,[i,o])}})}getConfig(){const e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}}iT.className="UpSampling2D";we(iT);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function HL(n,e,t=[1,1],s="valid",r,i){return le(()=>{r==null&&(r=Ei()),Gn(r);let o=$v(n,r);if(n.rank!==4)throw new Y(`Input for depthwiseConv2d is required to be 4-D, but is instead ${n.rank}-D`);if(e.rank!==4)throw new Y(`depthwiseKernel is required to be 4-D, but is instead ${e.rank}-D`);return o=L2(o,e,t,s==="same"?"same":"valid","NHWC",i),r==="channelsFirst"&&(o=qt(o,[0,3,1,2])),o})}class oT extends Um{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=In(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=ss(e.depthwiseConstraint),this.depthwiseRegularizer=En(e.depthwiseRegularizer)}build(e){if(e=Yt(e),e.length<4)throw new Y(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new Y(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const s=e[t],r=[this.kernelSize[0],this.kernelSize[1],s,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",r,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[s*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return le(()=>{e=yt(e);let s=HL(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(s=Mi(s,this.bias.read(),this.dataFormat)),this.activation!=null&&(s=this.activation.apply(s)),s})}computeOutputShape(e){e=Yt(e);const t=this.dataFormat==="channelsFirst"?e[2]:e[1],s=this.dataFormat==="channelsFirst"?e[3]:e[2],r=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,i=Si(t,this.kernelSize[0],this.padding,this.strides[0]),o=Si(s,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],r,i,o]:[e[0],i,o,r]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=An(this.depthwiseInitializer),e.depthwiseRegularizer=hn(this.depthwiseRegularizer),e.depthwiseConstraint=ns(this.depthwiseRegularizer),e}}oT.className="DepthwiseConv2D";we(oT);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function aT(n,e,t,s){if(Array.isArray(n)){if(e!=null||t!=null)throw new Y("When inputs is an array, neither initialState or constants should be provided");s!=null&&(t=n.slice(n.length-s,n.length),n=n.slice(0,n.length-s)),n.length>1&&(e=n.slice(1,n.length)),n=n[0]}function r(i){return i==null||Array.isArray(i)?i:[i]}return e=r(e),t=r(t),{inputs:n,initialState:e,constants:t}}function lT(n,e,t,s=!1,r,i,o=!1,a=!1){return le(()=>{const l=e.shape.length;if(l<3)throw new Y(`Input should be at least 3D, but is ${l}D.`);const c=[1,0].concat(Ii(2,l));e=qt(e,c),o&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),r!=null&&(r=qe(qe(r,"bool"),"float32"),r.rank===l-1&&(r=js(r,-1)),r=qt(r,c)),s&&(e=vl(e,0),r!=null&&(r=vl(r,0)));const u=[];let h,d=t;const p=e.shape[0],f=bl(e);let x;r!=null&&(x=bl(r));for(let g=0;gn(v,d));if(r==null)h=b[0],d=b[1];else{const y=le(()=>{const w=x[g],C=ft(ti(w),w),T=ke(Z(b[0],w),Z(d[0],C)),E=d.map((R,_)=>ke(Z(b[1][_],w),Z(R,C)));return{output:T,newStates:E}});h=y.output,d=y.newStates}a&&u.push(h)}let m;return a&&(m=Ji(u,1)),[h,m,d]})}class Ia extends Ot{constructor(e){super(e);let t;if(e.cell==null)throw new Y("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new Lv({cells:e.cell}):t=e.cell,t.stateSize==null)throw new Y("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences==null?!1:e.returnSequences,this.returnState=e.returnState==null?!1:e.returnState,this.goBackwards=e.goBackwards==null?!1:e.goBackwards,this._stateful=e.stateful==null?!1:e.stateful,this.unroll=e.unroll==null?!1:e.unroll,this.supportsMasking=!0,this.inputSpec=[new Jn({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return Ii(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){fx(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const s=t[0];let r;if(this.returnSequences?r=[e[0],e[1],s]:r=[e[0],s],this.returnState){const i=[];for(const o of t)i.push([e[0],o]);return[r].concat(i)}else return r}computeMask(e,t){return le(()=>{Array.isArray(t)&&(t=t[0]);const s=this.returnSequences?t:null;if(this.returnState){const r=this.states.map(i=>null);return[s].concat(r)}else return s})}get states(){if(this.states_==null){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let s=0;so.shape[o.shape.length-1]),i))throw new Y(`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=i.map(o=>new Jn({shape:[null,o]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){le(()=>{if(!this.stateful)throw new Pi("Cannot call resetStates() on an RNN Layer that is not stateful.");const s=this.inputSpec[0].shape[0];if(s==null)throw new Y("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(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(r=>On([s,r])):this.states_=[On([s,this.cell.stateSize])];else if(e==null)Nt(this.states_),this.keptStates!=null&&(Nt(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(r=>On([s,r])):this.states_[0]=On([s,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Y(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t===!0?this.keptStates.push(this.states_.slice()):Nt(this.states_);for(let r=0;rer(r.clone()))})}apply(e,t){let s=t==null?null:t.initialState,r=t==null?null:t.constants;t==null&&(t={});const i=aT(e,s,r,this.numConstants);e=i.inputs,s=i.initialState,r=i.constants;let o=[],a=[];if(s!=null){t.initialState=s,o=o.concat(s),this.stateSpec=[];for(const c of s)this.stateSpec.push(new Jn({shape:c.shape}));a=a.concat(this.stateSpec)}if(r!=null&&(t.constants=r,o=o.concat(r),this.numConstants=r.length),o[0]instanceof Qi){const c=[e].concat(o),u=this.inputSpec.concat(a),h=this.inputSpec;this.inputSpec=u;const d=super.apply(c,t);return this.inputSpec=h,d}else return super.apply(e,t)}call(e,t){return le(()=>{const s=t==null?null:t.mask,r=t==null?null:t.training;let i=t==null?null:t.initialState;e=yt(e),i==null&&(this.stateful?i=this.states_:i=this.getInitialState(e));const o=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(i.length!==o)throw new Y(`RNN Layer has ${o} state(s) but was passed ${i.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const a={training:r},c=lT((f,x)=>{const m=this.cell.call([f].concat(x),a);return[m[0],m.slice(1)]},e,i,this.goBackwards,s,null,this.unroll,this.returnSequences),u=c[0],h=c[1],d=c[2];this.stateful&&this.resetStates(d,r);const p=this.returnSequences?h:u;return this.returnState?[p].concat(d):p})}getInitialState(e){return le(()=>{let t=On(e.shape);return t=lt(t,[1,2]),t=lp(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(s=>s>1?dx(t,[1,s]):t):this.cell.stateSize>1?[dx(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),this.cell!=null&&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};this.numConstants!=null&&(t.numConstants=this.numConstants);const s=this.cell.getConfig();return this.getClassName()===Ia.className&&(t.cell={className:this.cell.getClassName(),config:s}),Object.assign(Object.assign(Object.assign({},s),e),t)}static fromConfig(e,t,s={}){const r=t.cell,i=To(r,s);return new e(Object.assign(t,{cell:i}))}}Ia.className="RNN";we(Ia);class Wm extends Ot{}class Dv extends Wm{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,us(this.units,"units"),this.activation=ua(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=In(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=In(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=In(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=En(e.kernelRegularizer),this.recurrentRegularizer=En(e.recurrentRegularizer),this.biasRegularizer=En(e.biasRegularizer),this.kernelConstraint=ss(e.kernelConstraint),this.recurrentConstraint=ss(e.recurrentConstraint),this.biasConstraint=ss(e.biasConstraint),this.dropout=Dc([1,la([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Dc([1,la([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Yt(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 le(()=>{if(e=e,e.length!==2)throw new Y(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let s=e[1];e=e[0];const r=t.training==null?!1:t.training;0ti(e),rate:this.dropout,training:r,dropoutFunc:this.dropoutFunc})),0ti(s),rate:this.recurrentDropout,training:r,dropoutFunc:this.dropoutFunc}));let i;const o=this.dropoutMask,a=this.recurrentDropoutMask;o!=null?i=qi(Z(e,o),this.kernel.read()):i=qi(e,this.kernel.read()),this.bias!=null&&(i=Mi(i,this.bias.read())),a!=null&&(s=Z(s,a));let l=ke(i,qi(s,this.recurrentKernel.read()));return this.activation!=null&&(l=this.activation.apply(l)),[l,l]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:ca(this.activation),useBias:this.useBias,kernelInitializer:An(this.kernelInitializer),recurrentInitializer:An(this.recurrentInitializer),biasInitializer:An(this.biasInitializer),kernelRegularizer:hn(this.kernelRegularizer),recurrentRegularizer:hn(this.recurrentRegularizer),biasRegularizer:hn(this.biasRegularizer),activityRegularizer:hn(this.activityRegularizer),kernelConstraint:ns(this.kernelConstraint),recurrentConstraint:ns(this.recurrentConstraint),biasConstraint:ns(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}Dv.className="SimpleRNNCell";we(Dv);class cT extends Ia{constructor(e){e.cell=new Dv(e),super(e)}call(e,t){return le(()=>{this.cell.dropoutMask!=null&&(Nt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Nt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=t==null?null:t.mask,r=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:s,training:r,initialState:i})})}static fromConfig(e,t){return new e(t)}}cT.className="SimpleRNN";we(cT);class Pv extends Wm{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 Y("GRUCell does not support reset_after parameter set to true.");this.units=e.units,us(this.units,"units"),this.activation=ua(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ua(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=In(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=In(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=In(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=En(e.kernelRegularizer),this.recurrentRegularizer=En(e.recurrentRegularizer),this.biasRegularizer=En(e.biasRegularizer),this.kernelConstraint=ss(e.kernelConstraint),this.recurrentConstraint=ss(e.recurrentConstraint),this.biasConstraint=ss(e.biasConstraint),this.dropout=Dc([1,la([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Dc([1,la([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Yt(e);const t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return le(()=>{if(e=e,e.length!==2)throw new Y(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const s=t.training==null?!1:t.training;let r=e[1];e=e[0],0ti(e),rate:this.dropout,training:s,count:3,dropoutFunc:this.dropoutFunc})),0ti(r),rate:this.recurrentDropout,training:s,count:3,dropoutFunc:this.dropoutFunc}));const i=this.dropoutMask,o=this.recurrentDropoutMask;let a,l,c;0{this.cell.dropoutMask!=null&&(Nt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Nt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=t==null?null:t.mask,r=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:s,training:r,initialState:i})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}uT.className="GRU";we(uT);class Gm extends Wm{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,us(this.units,"units"),this.activation=ua(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ua(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=In(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=In(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=In(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=En(e.kernelRegularizer),this.recurrentRegularizer=En(e.recurrentRegularizer),this.biasRegularizer=En(e.biasRegularizer),this.kernelConstraint=ss(e.kernelConstraint),this.recurrentConstraint=ss(e.recurrentConstraint),this.biasConstraint=ss(e.biasConstraint),this.dropout=Dc([1,la([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Dc([1,la([0,e.recurrentDropout==null?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;e=Yt(e);const s=e[e.length-1];this.kernel=this.addWeight("kernel",[s,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let r;if(this.useBias){if(this.unitForgetBias){const i=this.biasInitializer,o=this.units;r=new(t=class extends si{apply(l,c){const u=i.apply([o]),h=new wv().apply([o]),d=i.apply([o*2]);return Sy(Sy(u,h),d)}},t.className="CustomInit",t)}else r=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,r,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return le(()=>{const s=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new Y(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let r=e[1];const i=e[2];e=e[0],0ti(e),rate:this.dropout,training:s,count:4,dropoutFunc:this.dropoutFunc})),0ti(r),rate:this.recurrentDropout,training:s,count:4,dropoutFunc:this.dropoutFunc}));const o=this.dropoutMask,a=this.recurrentDropoutMask;let l,c,u,h;0{this.cell.dropoutMask!=null&&(Nt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Nt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=t==null?null:t.mask,r=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:s,training:r,initialState:i})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}hT.className="LSTM";we(hT);class Lv extends Wm{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 le(()=>{e=e;let s=e.slice(1);const r=[];for(const a of this.cells.slice().reverse())Array.isArray(a.stateSize)?r.push(s.splice(0,a.stateSize.length)):r.push(s.splice(0,1));r.reverse();const i=[];let o;for(let a=0;a{ol(`RNNCell_${r}`,()=>{s.build(e),Array.isArray(s.stateSize)?t=s.stateSize[0]:t=s.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){const e=super.getConfig(),t=i=>({className:i.getClassName(),config:i.getConfig()}),r={cells:this.cells.map(t)};return Object.assign(Object.assign({},e),r)}static fromConfig(e,t,s={}){const r=[];for(const i of t.cells)r.push(To(i,s));return new e({cells:r})}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 s of this.cells)t.push(...s.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return mx(e)}setWeights(e){const t=[];for(const s of this.cells){const r=s.weights.length,i=e.splice(r);for(let o=0;oi!=null?i(e(),t):n_(e(),t),a=()=>up(o,e,s);return!r||r<=1?er(a().clone()):Array(r).fill(void 0).map(a).map(c=>er(c.clone()))}/** + * @license + * Copyright 2020 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */var qL=function(n,e){var t={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(n);r{if(this.cell.dropoutMask!=null&&(Nt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Nt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new Y("ConvRNN2D cell does not support constants");const s=t==null?null:t.mask,r=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:s,training:r,initialState:i})})}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 le(()=>{const{stateSize:t}=this.cell,s=e.shape,r=this.computeSingleOutputShape(s),i=[r[0],...r.slice(2)],o=On(i);return Array.isArray(t)?Array(t.length).fill(o):[o]})}resetStates(e,t=!1){le(()=>{if(!this.stateful)throw new Pi("Cannot call resetStates() on an RNN Layer that is not stateful.");const s=this.inputSpec[0].shape,r=this.computeSingleOutputShape(s),i=[r[0],...r.slice(2)];if(s[0]==null)throw new Y("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(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>On(i)):this.states_=[On(i)];else if(e==null)Nt(this.states_),this.keptStates!=null&&(Nt(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>On(i)):this.states_[0]=On(i);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Y(`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()):Nt(this.states_);for(let a=0;aer(a.clone()))})}computeSingleOutputShape(e){const{dataFormat:t,filters:s,kernelSize:r,padding:i,strides:o,dilationRate:a}=this.cell,l=t==="channelsFirst",c=e[l?3:2],u=e[l?4:3],h=Si(c,r[0],i,o[0],a[0]),d=Si(u,r[1],i,o[1],a[1]);return[...e.slice(0,2),...l?[s,h,d]:[h,d,s]]}}dT.className="ConvRNN2D";class Fv extends Gm{constructor(e){const{filters:t,kernelSize:s,strides:r,padding:i,dataFormat:o,dilationRate:a}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,us(this.filters,"filters"),this.kernelSize=Cc(s,2,"kernelSize"),this.kernelSize.forEach(l=>us(l,"kernelSize")),this.strides=Cc(r||1,2,"strides"),this.strides.forEach(l=>us(l,"strides")),this.padding=i||"valid",Pr(this.padding),this.dataFormat=o||"channelsLast",Gn(this.dataFormat),this.dilationRate=Cc(a||1,2,"dilationRate"),this.dilationRate.forEach(l=>us(l,"dilationRate"))}build(e){var t;e=Yt(e);const s=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[s]==null)throw new Y(`The channel dimension of the input should be defined. Found ${e[s]}`);const r=e[s],i=4,o=this.kernelSize.concat([r,this.filters*i]);this.kernel=this.addWeight("kernel",o,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const a=this.kernelSize.concat([this.filters,this.filters*i]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",a,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let l;if(this.unitForgetBias){const c=this.biasInitializer,u=this.filters;l=new(t=class extends si{apply(d,p){const f=c.apply([u]),x=_a([u]),m=c.apply([u*2]);return yv([f,x,m])}},t.className="CustomInit",t)}else l=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*i],null,l,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return le(()=>{if(e.length!==3)throw new Y(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const s=t.training||!1,r=e[0],i=e[1],o=e[2],a=4;0ti(r),rate:this.dropout,training:s,count:a,dropoutFunc:this.dropoutFunc}));const l=this.dropoutMask,c=(K,J,ae)=>!J||!J[ae]?K:Z(J[ae],K);let u=c(r,l,0),h=c(r,l,1),d=c(r,l,2),p=c(r,l,3);0ti(i),rate:this.recurrentDropout,training:s,count:a,dropoutFunc:this.dropoutFunc}));const f=this.recurrentDropoutMask;let x=c(i,f,0),m=c(i,f,1),g=c(i,f,2),v=c(i,f,3);const b=3,[y,w,C,T]=kr(this.kernel.read(),a,b),[E,R,_,k]=this.useBias?kr(this.bias.read(),a):[null,null,null,null];u=this.inputConv(u,y,E,this.padding),h=this.inputConv(h,w,R,this.padding),d=this.inputConv(d,C,_,this.padding),p=this.inputConv(p,T,k,this.padding);const[F,B,M,P]=kr(this.recurrentKernel.read(),a,b);x=this.recurrentConv(x,F),m=this.recurrentConv(m,B),g=this.recurrentConv(g,M),v=this.recurrentConv(v,P);const L=this.recurrentActivation.apply(ke(u,x)),q=this.recurrentActivation.apply(ke(h,m)),U=ke(Z(q,o),Z(L,this.activation.apply(ke(d,g)))),X=Z(this.recurrentActivation.apply(ke(p,v)),this.activation.apply(U));return[X,X,U]})}getConfig(){const e=super.getConfig(),{units:t}=e,s=qL(e,["units"]),r={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},s),r)}inputConv(e,t,s,r){const i=gl(e,t,this.strides,r||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return s?Mi(i,s,this.dataFormat):i}recurrentConv(e,t){return gl(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}}Fv.className="ConvLSTM2DCell";we(Fv);class pT extends dT{constructor(e){const t=new Fv(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}}pT.className="ConvLSTM2D";we(pT);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Ov extends Ot{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(this.noiseShape==null)return this.noiseShape;const t=e.shape,s=[];for(let r=0;r{this.invokeCallHook(e,t);const s=yt(e);if(0n_(s,this.rate,i,this.seed),()=>s,r)}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()}}Ov.className="Dropout";we(Ov);class fT extends Ov{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}fT.className="SpatialDropout1D";we(fT);class mT extends Ot{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",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,us(this.units,"units"),this.activation=ua(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=In(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=In(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=ss(e.kernelConstraint),this.biasConstraint=ss(e.biasConstraint),this.kernelRegularizer=En(e.kernelRegularizer),this.biasRegularizer=En(e.biasRegularizer),this.activityRegularizer=En(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=Yt(e);const t=e[e.length-1];this.kernel==null&&(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){e=Yt(e);const t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return le(()=>{this.invokeCallHook(e,t);const s=yt(e),r=j4(this.activation.getClassName());let i;return r!=null?i=qi(s,this.kernel.read(),r,this.bias?this.bias.read():null):(i=qi(s,this.kernel.read()),this.bias!=null&&(i=Mi(i,this.bias.read())),this.activation!=null&&(i=this.activation.apply(i))),i})}getConfig(){const e={units:this.units,activation:ca(this.activation),useBias:this.useBias,kernelInitializer:An(this.kernelInitializer),biasInitializer:An(this.biasInitializer),kernelRegularizer:hn(this.kernelRegularizer),biasRegularizer:hn(this.biasRegularizer),activityRegularizer:hn(this.activityRegularizer),kernelConstraint:ns(this.kernelConstraint),biasConstraint:ns(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}mT.className="Dense";we(mT);class gT extends Ot{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=Yt(e);for(const t of e.slice(1))if(t==null)throw new Y(`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],na(e,1)]}call(e,t){return le(()=>{this.invokeCallHook(e,t);let s=yt(e);if(this.dataFormat==="channelsFirst"&&s.rank>1){const r=[0];for(let i=2;i{this.invokeCallHook(e,t);const s=yt(e);return this.activation.apply(s)})}getConfig(){const e={activation:ca(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}xT.className="Activation";we(xT);class vT extends Ot{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 le(()=>(e=yt(e),_8(e,this.n)))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}vT.className="RepeatVector";we(vT);class bT extends Ot{constructor(e){super(e),this.targetShape=e.targetShape;for(let t=0;t{this.invokeCallHook(e,t);const s=yt(e),r=s.shape,i=r.slice(0,1).concat(this.fixUnknownDimension(r.slice(1),this.targetShape));return se(s,i)})}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}bT.className="Reshape";we(bT);class yT extends Ot{constructor(e){if(super(e),e.dims==null)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=Ii(1,e.dims.length+1);if(!Wt(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 Jn({ndim:this.dims.length+1})]}computeOutputShape(e){e=Yt(e);const t=e.slice();return this.dims.forEach((s,r)=>{t[r+1]=e[s]}),t}call(e,t){return qt(yt(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}yT.className="Permute";we(yT);class wT extends Ot{constructor(e){super(e??{}),this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.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 s=yt(e);return ix(Ff(s,this.maskValue),-1)}call(e,t){return le(()=>{this.invokeCallHook(e,t);const s=yt(e),o=ix(Ff(s,this.maskValue),-1,!0);return Z(s,qe(o,s.dtype))})}}wT.className="Masking";we(wT);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class ST extends Ot{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(nn(e.inputLength))}this.inputDim=e.inputDim,us(this.inputDim,"inputDim"),this.outputDim=e.outputDim,us(this.outputDim,"outputDim"),this.embeddingsInitializer=In(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=En(e.embeddingsRegularizer),this.activityRegularizer=En(e.activityRegularizer),this.embeddingsConstraint=ss(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 le(()=>this.maskZero?(e=yt(e),Ff(e,Xt(e))):null)}computeOutputShape(e){if(e=Yt(e),this.inputLength==null)return[...e,this.outputDim];const t=nn(this.inputLength);if(t.length!==e.length-1)throw new Y(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let s=0;for(let r=0;r{this.invokeCallHook(e,t);let s=yt(e);s.dtype!=="int32"&&(s=Hi(s,"int32"));const r=t_(this.embeddings.read(),se(s,[s.size]));return se(r,Yt(this.computeOutputShape(s.shape)))})}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:An(this.embeddingsInitializer),embeddingsRegularizer:hn(this.embeddingsRegularizer),activityRegularizer:hn(this.activityRegularizer),embeddingsConstraint:ns(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}ST.className="Embedding";we(ST);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class Ol extends Ot{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Mt}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length1)throw new Y(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let s=e[0]==null?null:e[0].slice(1);for(let i=1;ii.length);e.indexOf(null)===-1&&ta(r).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return le(()=>{if(e=e,this.reshapeRequired){const s=[],r=e.map(i=>i.rank);if(r.indexOf(null)===-1){const i=la(r);for(let o of e){const a=o.rank;for(let l=0;l1){const u=Ii(1,c).concat([0]);s.push(qt(l,u)),i=!0}else s.push(l)}let o=this.mergeFunction(s);const a=o.rank;if(i){if(a==null){const l=o.shape,c=l.length,u=l[c-1],h=[u].concat(l.slice(0,l.length-1));o=se(qt(se(o,[-1,u]),[1,0]),h)}else if(a>1){const l=[a-1].concat(Ii(0,a-1));o=qt(o,l)}}return o}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let r=1;r{if(t==null)return null;if(!Array.isArray(t))throw new Y("`mask` should be an Array");if(!Array.isArray(e))throw new Y("`inputs` should be an Array");if(t.length!==e.length)throw new Y(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(r=>r==null))return null;t=t.map(r=>r==null?r:js(r,0));let s=t[0];for(let r=1;r{let t=e[0].clone();for(let s=1;s{let t=e[0].clone();for(let s=1;s{let t=e[0].clone();for(let s=1;s{let t=e[0];for(let s=1;s{let t=e[0];for(let s=1;s1)throw new Y("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return le(()=>yv(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new Y("A `Concatenate` layer should be called on a list of inputs.");const t=e,s=t[0].slice(),r=this.axis<0?s.length+this.axis:this.axis;for(const i of t.slice(1)){if(s[r]==null||i[r]==null){s[r]=null;break}s[r]+=i[r]}return s}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new Y("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new Y("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new Y(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return le(()=>{let s=!0;if(t.forEach(o=>{if(o!=null){s=!1;return}}),s)return null;const r=[];for(let o=0;o3||e.shape.length>3)throw new Mt("batchDot is not implemented for tensors of 4D or higher rank yet");if(N(n.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${n.shape.length}`),N(n.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${e.shape.length}`),typeof t=="number"&&(t=[t,t]),n.dtype==="complex64"||e.dtype==="complex64")throw new Mt("batchDot is not implemented for complex64-type Tensors yet.");const s=n.shape.length,r=e.shape.length;t==null&&(t=[s-1,r-2]);const i=t;return le(()=>{let o;if(s>r){o=s-r;const l=[];for(let c=0;cs){o=r-s;const l=[];for(let c=0;c0){let l;s>r?l=s+r-3:l=s-1;const c=[];for(let u=l;u"A `Dot` layer should be called on a list of exactly 2 inputs.");const t=e[0],s=e[1];if(t.length>3||s.length>3)throw new Mt("Dot layer does not support tensors of 4D or higher rank yet.");const r=this.interpretAxes(t,s);if(t[r[0]]!==s[r[1]])throw new Y(`Dimension incompatibility: ${t[r[0]]} !== ${s[r[1]]}`)}mergeFunction(e){if(e.length!==2)throw new Y(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],s=e[1],r;return Array.isArray(this.axes)?r=this.axes.map((i,o)=>gh(i,e[o].shape.length)):r=[gh(this.axes,t.shape.length),gh(this.axes,s.shape.length)],this.normalize&&(t=Gf(t,r[0]),s=Gf(s,r[1])),XL(t,s,r)}interpretAxes(e,t){let s;return Array.isArray(this.axes)?s=this.axes:s=[gh(this.axes,e.length),gh(this.axes,t.length)],s}computeOutputShape(e){N(Array.isArray(e)&&e.length===2&&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(),s=e[1].slice();if(t.length>3||s.length>3)throw new Mt("Dot layer does not support tensors of 4D or higher rank yet.");const r=this.interpretAxes(t,s);t.splice(r[0],1),s.splice(r[1],1),s.splice(0,1);const i=t.concat(s);return i.length===1&&i.push(1),i}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}AT.className="Dot";we(AT);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class RT extends Ot{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 le(()=>{this.invokeCallHook(e,t);const s=yt(e);return up(()=>ke(Fm(s.shape,0,this.stddev),s),()=>s,t.training||!1)})}}RT.className="GaussianNoise";we(RT);class MT extends Ot{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 le(()=>{this.invokeCallHook(e,t);const s=yt(e);return this.rate>0&&this.rate<1?up(()=>{const i=Math.sqrt(this.rate/(1-this.rate));return Z(s,Fm(s.shape,1,i))},()=>s,t.training||!1):s})}}MT.className="GaussianDropout";we(MT);class NT extends Ot{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||yt(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 le(()=>{if(this.rate<1&&this.rate>0){const s=this._getNoiseShape(e);return up(()=>{const i=yt(e),a=-1.6732632423543772*1.0507009873554805;let l=Ml(aa(s),this.rate);l=Hi(l,"float32");const c=((1-this.rate)*(1+this.rate*a**2))**-.5,u=-c*a*this.rate,h=ke(Z(i,l),Z(ke(l,-1),a));return ke(Z(h,c),u)},()=>yt(e),t.training||!1)}return e})}}NT.className="AlphaDropout";we(NT);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function Hh(n,e,t,s,r,i=.001){let o;if(n.rank===2)o=wN(n,e,t,s,r,i);else if(n.rank===3)o=CN(n,e,t,s,r,i);else if(n.rank===4)o=TN(n,e,t,s,r,i);else throw new Mt(`batchNormalization is not implemented for array of rank ${n.rank} yet`);return o}function KL(n,e,t,s,r=.001){return le(()=>{const i=W2(n,s),o=i.mean,a=i.variance;return[Hh(n,o,a,t,e,r),o,a]})}function jL(n,e,t,s,r=.001){return le(()=>{const i=W2(n,s),o=i.mean,a=i.variance,l=[];for(const f of Ii(0,n.rank))s.indexOf(f)!==-1?l.push(1):l.push(n.shape[f]);const c=se(o,l),u=se(a,l),h=e==null?null:se(e,l),d=t==null?null:se(t,l);return[Hh(n,c,u,d,h,r),o,a]})}function YL(n,e,t,s,r=.001){return Wt(s.slice().sort(),Ii(0,n.rank-1))?KL(n,e,t,s,r):jL(n,e,t,s,r)}class $T extends Ot{constructor(e){e==null&&(e={}),super(e),this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=In(e.betaInitializer||"zeros"),this.gammaInitializer=In(e.gammaInitializer||"ones"),this.movingMeanInitializer=In(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=In(e.movingVarianceInitializer||"ones"),this.betaConstraint=ss(e.betaConstraint),this.gammaConstraint=ss(e.gammaConstraint),this.betaRegularizer=En(e.betaRegularizer),this.gammaRegularizer=En(e.gammaRegularizer)}build(e){e=Yt(e);const t=this.axis>=0?this.axis:this.axis+e.length,s=e[t];if(s==null)throw new Y(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Jn({ndim:e.length,axes:{[t]:s}})];const r=[s];this.scale&&(this.gamma=this.addWeight("gamma",r,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",r,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",r,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",r,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return le(()=>{const s=t.training==null?!1:t.training,r=yt(e),i=r.shape,o=i.length,a=Ii(0,o),l=this.axis>=0?this.axis:this.axis+o;a.splice(l,1);const c=wl(1,o);c[l]=i[l];const u=a.slice();u.sort();const h=!Wt(u,Ii(0,o).slice(0,o-1)),d=()=>{if(h){const v=se(this.movingMean.read(),c),b=se(this.movingVariance.read(),c),y=this.center?se(this.beta.read(),c):null,w=this.scale?se(this.gamma.read(),c):null;return Hh(r,v,b,y,w,this.epsilon)}else return Hh(r,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!s)return d();const[p,f,x]=YL(r,this.gamma.read(),this.beta.read(),a,this.epsilon),m=(v,b,y)=>{le(()=>{const w=1-y,C=v.read(),T=Z(ft(C,b),w);v.write(ft(C,T))})};return(()=>{m(this.movingMean,f,this.momentum),m(this.movingVariance,x,this.momentum)})(),p})}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:An(this.betaInitializer),gammaInitializer:An(this.gammaInitializer),movingMeanInitializer:An(this.movingMeanInitializer),movingVarianceInitializer:An(this.movingVarianceInitializer),betaRegularizer:hn(this.betaRegularizer),gammaRegularizer:hn(this.gammaRegularizer),betaConstraint:ns(this.betaConstraint),gammaConstraint:ns(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}$T.className="BatchNormalization";we($T);class DT extends Ot{constructor(e){if(e==null&&(e={}),super(e),this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(const t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=In(e.betaInitializer||"zeros"),this.gammaInitializer=In(e.gammaInitializer||"ones"),this.betaRegularizer=En(e.betaRegularizer),this.gammaRegularizer=En(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=Yt(e);const t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let i=0;i=t)throw new Error(`Invalid axis: ${i}`);if(this.axis.length!==ta(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const s=this.axis.map(i=>e[i]),r=!0;this.scale?this.gamma=this.addWeight("gamma",s,"float32",this.gammaInitializer,this.gammaRegularizer,r):this.gamma=null,this.center?this.beta=this.addWeight("beta",s,"float32",this.betaInitializer,this.betaRegularizer,r):this.beta=null,this.built=!0}call(e,t){const s=yt(e),r=s.shape,i=r.length;return le(()=>{let{mean:a,variance:l}=W2(s,this.axis,!0);const c=wl(1,i);for(const x of this.axis)c[x]=r[x];const u=x=>x!=null&&x.shape.length!==i?se(x,c):x;let h=this.scale?u(this.gamma.read()):null,d=this.center?u(this.beta.read()):null;const p=[],f=[];for(let x=0;x{if(n.rank!==4)throw new Y(`temporalPadding expects input tensor to be 4-D, but received a ${n.rank}-D tensor.`);if(e==null&&(e=[[1,1],[1,1]]),e.length!==2||e[0].length!==2||e[1].length!==2)throw new Y("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(t==null&&(t=Ei()),t!=="channelsLast"&&t!=="channelsFirst")throw new Y(`Unknown data format: ${t}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let s;return t==="channelsFirst"?s=[[0,0],[0,0],e[0],e[1]]:s=[[0,0],e[0],e[1],[0,0]],G2(n,s)})}class PT extends Ot{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?Ei():e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new Y(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,s;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],s=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new Y(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],e.padding[1].length!==2)throw new Y(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);s=e.padding[1]}this.padding=[t,s]}this.inputSpec=[new Jn({ndim:4})]}computeOutputShape(e){e=Yt(e);let t,s;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?s=e[3]+this.padding[1][0]+this.padding[1][1]:s=null,[e[0],e[1],t,s]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?s=e[2]+this.padding[1][0]+this.padding[1][1]:s=null,[e[0],t,s,e[3]])}call(e,t){return le(()=>ZL(yt(e),this.padding,this.dataFormat))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}PT.className="ZeroPadding2D";we(PT);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function Hm(n,e,t,s,r,i){return le(()=>{Gn(r),Z4(i),Pr(s),t==null&&(t=[1,1]),s==null&&(s="valid"),r==null&&(r=Ei()),i==null&&(i="max"),n=$v(n,r);let o;const a=s==="same"?"same":"valid";return i==="max"?o=V2(n,e,t,a):o=N2(n,e,t,a),r==="channelsFirst"&&(o=qt(o,[0,3,1,2])),o})}function LT(n,e,t,s,r,i){return le(()=>{Gn(r),Z4(i),Pr(s),t==null&&(t=[1,1,1]),s==null&&(s="valid"),r==null&&(r=Ei()),i==null&&(i="max"),n=Q_(n,r);let o;const a=s==="same"?"same":"valid";return i==="max"?o=c6(n,e,t,a):o=hN(n,e,t,a),r==="channelsFirst"&&(o=qt(o,[0,4,1,2,3])),o})}class FT extends Ot{constructor(e){if(e.poolSize==null&&(e.poolSize=2),super(e),typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new Y(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(us(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")this.strides=e.strides;else throw new Y(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);us(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Pr(this.padding),this.inputSpec=[new Jn({ndim:3})]}computeOutputShape(e){e=Yt(e);const t=Si(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return le(()=>{this.invokeCallHook(e,t),e=lp(yt(e),2);const s=this.poolingFunction(yt(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return sp(s,[2])})}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class OT extends FT{constructor(e){super(e)}poolingFunction(e,t,s,r,i){return Gn(i),Pr(r),Hm(e,t,s,r,i,"max")}}OT.className="MaxPooling1D";we(OT);class zT extends FT{constructor(e){super(e)}poolingFunction(e,t,s,r,i){return Gn(i),Pr(r),Hm(e,t,s,r,i,"avg")}}zT.className="AveragePooling1D";we(zT);class BT extends Ot{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new Y(`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];us(this.poolSize,"poolSize"),us(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Gn(this.dataFormat),Pr(this.padding),this.inputSpec=[new Jn({ndim:4})]}computeOutputShape(e){e=Yt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],s=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Si(t,this.poolSize[0],this.padding,this.strides[0]),s=Si(s,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,s]:[e[0],t,s,e[3]]}call(e,t){return le(()=>(this.invokeCallHook(e,t),this.poolingFunction(yt(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 UT extends BT{constructor(e){super(e)}poolingFunction(e,t,s,r,i){return Gn(i),Pr(r),Hm(e,t,s,r,i,"max")}}UT.className="MaxPooling2D";we(UT);class VT extends BT{constructor(e){super(e)}poolingFunction(e,t,s,r,i){return Gn(i),Pr(r),Hm(e,t,s,r,i,"avg")}}VT.className="AveragePooling2D";we(VT);class WT extends Ot{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new Y(`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];us(this.poolSize,"poolSize"),us(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Gn(this.dataFormat),Pr(this.padding),this.inputSpec=[new Jn({ndim:5})]}computeOutputShape(e){e=Yt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],s=this.dataFormat==="channelsFirst"?e[3]:e[2],r=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=Si(t,this.poolSize[0],this.padding,this.strides[0]),s=Si(s,this.poolSize[1],this.padding,this.strides[1]),r=Si(r,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,s,r]:[e[0],t,s,r,e[4]]}call(e,t){return le(()=>(this.invokeCallHook(e,t),this.poolingFunction(yt(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 GT extends WT{constructor(e){super(e)}poolingFunction(e,t,s,r,i){return Gn(i),Pr(r),LT(e,t,s,r,i,"max")}}GT.className="MaxPooling3D";we(GT);class HT extends WT{constructor(e){super(e)}poolingFunction(e,t,s,r,i){return Gn(i),Pr(r),LT(e,t,s,r,i,"avg")}}HT.className="AveragePooling3D";we(HT);class qT extends Ot{constructor(e){super(e),this.inputSpec=[new Jn({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Mt}}class XT extends qT{constructor(e){super(e||{})}call(e,t){return le(()=>{const s=yt(e);return Xn(s,1)})}}XT.className="GlobalAveragePooling1D";we(XT);class KT extends qT{constructor(e){super(e||{})}call(e,t){return le(()=>{const s=yt(e);return wi(s,1)})}}KT.className="GlobalMaxPooling1D";we(KT);class jT extends Ot{constructor(e){super(e),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Gn(this.dataFormat),this.inputSpec=[new Jn({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Mt}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class YT extends jT{call(e,t){return le(()=>{const s=yt(e);return this.dataFormat==="channelsLast"?Xn(s,[1,2]):Xn(s,[2,3])})}}YT.className="GlobalAveragePooling2D";we(YT);class ZT extends jT{call(e,t){return le(()=>{const s=yt(e);return this.dataFormat==="channelsLast"?wi(s,[1,2]):wi(s,[2,3])})}}ZT.className="GlobalMaxPooling2D";we(ZT);/** + * @license + * Copyright 2018 Google LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class JT extends Ot{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(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),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,s={}){const r=t.layer,i=To(r,s);delete t.layer;const o={layer:i};return Object.assign(o,t),new e(o)}}class QT extends JT{constructor(e){super(e),this.supportsMasking=!0}build(e){if(e=Yt(e),e.length<3)throw new Y(`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){e=Yt(e);const t=[e[0]].concat(e.slice(2)),s=this.layer.computeOutputShape(t),r=e[1];return[s[0],r].concat(s.slice(1))}call(e,t){return le(()=>(e=yt(e),lT((o,a)=>[yt(this.layer.call(o,t)),[]],e,[],!1,null,null,!1,!0)[1]))}}QT.className="TimeDistributed";we(QT);function JL(n){Fl(b8,"BidirectionalMergeMode",n)}const QL="concat";class eI extends JT{constructor(e){super(e);const t=e.layer.getConfig(),s={};s.className=e.layer.getClassName(),s.config=t,this.forwardLayer=To(s),t.goBackwards=t.goBackwards!==!0;const r={};if(r.className=e.layer.getClassName(),r.config=t,this.backwardLayer=To(r),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?QL:e.mergeMode,JL(this.mergeMode),e.weights)throw new Mt("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,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,s=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,s)),this.backwardLayer.setWeights(e.slice(s))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let s,r,i;return this.returnState&&(i=t.slice(1)),s=t[0],s=s,this.mergeMode==="concat"?(s[s.length-1]*=2,r=[s]):this.mergeMode==null?r=[s,s.slice()]:r=[s],this.returnState?this.mergeMode==null?r.concat(i).concat(i.slice()):[s].concat(i).concat(i.slice()):Ys(r)}apply(e,t){let s=t==null?null:t.initialState,r=t==null?null:t.constants;t==null&&(t={});const i=aT(e,s,r,this.numConstants);if(e=i.inputs,s=i.initialState,r=i.constants,Array.isArray(e)&&(s=e.slice(1),e=e[0]),(s==null||s.length===0)&&r==null)return super.apply(e,t);const o=[],a=[];if(s!=null){const c=s.length;if(c%2>0)throw new Y("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=s,o.push(...s);const u=s.map(h=>new Jn({shape:h.shape}));this.forwardLayer.stateSpec=u.slice(0,c/2),this.backwardLayer.stateSpec=u.slice(c/2),a.push(...u)}if(r!=null)throw new Mt("Support for constants in Bidirectional layers is not implemented yet.");const l=o[0]instanceof Qi;for(const c of o)if(c instanceof Qi!==l)throw new Y("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(l){const c=[e].concat(o),u=this.inputSpec.concat(a),h=this.inputSpec;this.inputSpec=u;const d=super.apply(c,t);return this.inputSpec=h,d}else return super.apply(e,t)}call(e,t){return le(()=>{const s=t.initialState;let r,i;if(s==null)r=this.forwardLayer.call(e,t),i=this.backwardLayer.call(e,t);else{const l=s.slice(0,s.length/2),c=s.slice(s.length/2);r=this.forwardLayer.call(e,Object.assign(t,{initialState:l})),i=this.backwardLayer.call(e,Object.assign(t,{initialState:c}))}let o;this.returnState&&(Array.isArray(r)&&(o=r.slice(1).concat(i.slice(1))),r=r[0],i=i[0]),this.returnSequences&&(i=vl(i,1));let a;return this.mergeMode==="concat"?a=yv([r,i]):this.mergeMode==="sum"?a=ke(r,i):this.mergeMode==="ave"?a=Z(.5,ke(r,i)):this.mergeMode==="mul"?a=Z(r,i):this.mergeMode==null&&(a=[r,i]),this.returnState?this.mergeMode==null?a.concat(o):[a].concat(o):a})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){ol(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),ol(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let s;if(this.returnSequences?this.mergeMode==null?s=[t,t]:s=t:this.mergeMode==null?s=[null,null]:s=null,this.returnState){const i=this.forwardLayer.states.map(o=>null);return Array.isArray(s)?s.concat(i).concat(i):[s].concat(i).concat(i)}else return s}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),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const s=To(t.layer);if(delete t.layer,t.numConstants!=null)throw new Mt("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const r=t;return r.layer=s,new e(r)}}eI.className="Bidirectional";we(eI);/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class tI extends Ot{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 le(()=>(e=yt(e),e.dtype!=="float32"&&(e=Hi(e,"float32")),ke(Z(e,this.scale),this.offset)))}}tI.className="Rescaling";we(tI);/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const{resizeBilinear:eF,cropAndResize:tF}=So;class nI extends Ot{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,s,r,i,o,a,l){return le(()=>{let c,u=!1;const h=t/o,d=s/a,p=(r+t)/o,f=(i+s)/a,x=[h,d,p,f],m=[];e.rank===3?(u=!0,c=Ji([e])):c=e;for(let w=0;w{const i=eF(e,[t,s]);return Hi(i,r)})}call(e,t){return le(()=>{const s=yt(e),r=s.dtype,i=s.shape,o=i[i.length-3],a=i[i.length-2];let l=0;o!==this.height&&(l=Math.floor((o-this.height)/2));let c=0;return a!==this.width&&(c=Math.floor((a-this.width)/2),c===0&&(c=1)),l>=0&&c>=0?this.centerCrop(s,l,c,this.height,this.width,o,a,r):this.upsize(e,this.height,this.width,r)})}getConfig(){const e={height:this.height,width:this.width},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){e=Yt(e);const t=e.length-3,s=e.length-2;return e[t]=this.height,e[s]=this.width,e}}nI.className="CenterCrop";we(nI);/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */function nF(n,e,t,s){let r=yt(n);if(r.dtype!=="int32"&&(r=Hi(r,"int32")),e==="int")return r;const i=r.shape;if(r.rank===0&&(r=js(r,-1)),e==="oneHot"&&r.shape[r.shape.length-1]!==1&&(r=js(r,-1)),r.rank>2)throw new Y(`When outputMode is not int, maximum output rank is 2 Received outputMode ${e} and input shape ${i} which would result in output rank ${r.rank}.`);const o=["multiHot","oneHot"].includes(e),a=r;let l;if(typeof s<"u"&&e==="count"?l=ry(a,s,t,o):l=ry(a,[],t,o),e!=="tfIdf")return l;if(s)return Z(l,s);throw new Y("When outputMode is 'tfIdf', weights must be provided.")}/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class sI extends Ot{constructor(e){super(e),this.numTokens=e.numTokens,e.outputMode?this.outputMode=e.outputMode:this.outputMode="multiHot"}getConfig(){const e={numTokens:this.numTokens,outputMode:this.outputMode},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){return e=Yt(e),e==null?[this.numTokens]:this.outputMode==="oneHot"&&e[e.length-1]!==1?(e.push(this.numTokens),e):(e[e.length-1]=this.numTokens,e)}call(e,t){return le(()=>{e=yt(e),e.dtype!=="int32"&&(e=Hi(e,"int32"));let s;if(typeof t.countWeights<"u"){if(this.outputMode!=="count")throw new Y(`countWeights is not used when outputMode !== count. + Received countWeights=${t.countWeights}`);s=yt(t.countWeights)}const r=wi(e),i=Pf(e),o=Dr(this.numTokens,r).bufferSync().get(0),a=Ml(i,0).bufferSync().get(0);if(!(o&&a))throw new Y(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return nF(e,this.outputMode,this.numTokens,s)})}}sI.className="CategoryEncoding";we(sI);/** + * @license + * Copyright 2022 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const sF=["bilinear","nearest"],By=new Set(sF);class rI extends Ot{constructor(e){if(super(e),this.height=e.height,this.width=e.width,e.interpolation)if(By.has(e.interpolation))this.interpolation=e.interpolation;else throw new Y(`Invalid interpolation parameter: ${e.interpolation} is not implemented`);else this.interpolation="bilinear";this.cropToAspectRatio=!!e.cropToAspectRatio}computeOutputShape(e){e=Yt(e);const t=e[2];return[this.height,this.width,t]}getConfig(){const e={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return le(()=>{const s=[this.height,this.width];if(this.interpolation==="bilinear")return So.resizeBilinear(e,s,!this.cropToAspectRatio);if(this.interpolation==="nearest")return So.resizeNearestNeighbor(e,s,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...By]} are supported`)})}}rI.className="Resizing";we(rI);/** + * @license + * Copyright 2023 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class iI{constructor(e){this.seed=e}next(){if(this.seed!==void 0)return this.seed++}}iI.className="RandomSeed";/** + * @license + * Copyright 2023 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */class oI extends Ot{constructor(e){super(e),this.randomGenerator=new iI(e.seed)}getConfig(){const e={seed:this.randomGenerator.seed},t=super.getConfig();return Object.assign(e,t),e}}oI.className="BaseRandomLayer";/** + * @license + * Copyright 2023 CodeSmith LLC + * + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. + * ============================================================================= + */const rF=["bilinear","nearest"],Uy=new Set(rF);class aI extends oI{constructor(e){super(e);const{factor:t,interpolation:s="bilinear"}=e;if(this.factor=t,Array.isArray(this.factor)&&this.factor.length===2)this.widthLower=this.factor[0],this.widthUpper=this.factor[1];else if(!Array.isArray(this.factor)&&this.factor>0)this.widthLower=-this.factor,this.widthUpper=this.factor;else throw new Y(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);if(this.widthLower<-1||this.widthUpper<-1)throw new Y(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper{const s=yt(e);this.imgHeight=s.shape[s.shape.length-3];const r=s.shape[s.shape.length-2];this.widthFactor=aa([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let i=this.widthFactor.dataSync()[0]*r;i=Math.round(i);const o=[this.imgHeight,i];switch(this.interpolation){case"bilinear":return So.resizeBilinear(e,o);case"nearest":return So.resizeNearestNeighbor(e,o);default:throw new Error(`Interpolation is ${this.interpolation} + but only ${[...Uy]} are supported`)}})}}aI.className="RandomWidth";we(aI);/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iF=oe();iF.registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,n=>{n&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")});/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */var Vy;(function(n){n[n.DT_INVALID=0]="DT_INVALID",n[n.DT_FLOAT=1]="DT_FLOAT",n[n.DT_DOUBLE=2]="DT_DOUBLE",n[n.DT_INT32=3]="DT_INT32",n[n.DT_UINT8=4]="DT_UINT8",n[n.DT_INT16=5]="DT_INT16",n[n.DT_INT8=6]="DT_INT8",n[n.DT_STRING=7]="DT_STRING",n[n.DT_COMPLEX64=8]="DT_COMPLEX64",n[n.DT_INT64=9]="DT_INT64",n[n.DT_BOOL=10]="DT_BOOL",n[n.DT_QINT8=11]="DT_QINT8",n[n.DT_QUINT8=12]="DT_QUINT8",n[n.DT_QINT32=13]="DT_QINT32",n[n.DT_BFLOAT16=14]="DT_BFLOAT16",n[n.DT_QINT16=15]="DT_QINT16",n[n.DT_QUINT16=16]="DT_QUINT16",n[n.DT_UINT16=17]="DT_UINT16",n[n.DT_COMPLEX128=18]="DT_COMPLEX128",n[n.DT_HALF=19]="DT_HALF",n[n.DT_RESOURCE=20]="DT_RESOURCE",n[n.DT_VARIANT=21]="DT_VARIANT",n[n.DT_UINT32=22]="DT_UINT32",n[n.DT_UINT64=23]="DT_UINT64",n[n.DT_FLOAT_REF=101]="DT_FLOAT_REF",n[n.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",n[n.DT_INT32_REF=103]="DT_INT32_REF",n[n.DT_UINT8_REF=104]="DT_UINT8_REF",n[n.DT_INT16_REF=105]="DT_INT16_REF",n[n.DT_INT8_REF=106]="DT_INT8_REF",n[n.DT_STRING_REF=107]="DT_STRING_REF",n[n.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",n[n.DT_INT64_REF=109]="DT_INT64_REF",n[n.DT_BOOL_REF=110]="DT_BOOL_REF",n[n.DT_QINT8_REF=111]="DT_QINT8_REF",n[n.DT_QUINT8_REF=112]="DT_QUINT8_REF",n[n.DT_QINT32_REF=113]="DT_QINT32_REF",n[n.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",n[n.DT_QINT16_REF=115]="DT_QINT16_REF",n[n.DT_QUINT16_REF=116]="DT_QUINT16_REF",n[n.DT_UINT16_REF=117]="DT_UINT16_REF",n[n.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",n[n.DT_HALF_REF=119]="DT_HALF_REF",n[n.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",n[n.DT_VARIANT_REF=121]="DT_VARIANT_REF",n[n.DT_UINT32_REF=122]="DT_UINT32_REF",n[n.DT_UINT64_REF=123]="DT_UINT64_REF"})(Vy||(Vy={}));var Wy;(function(n){(function(e){e[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"})(n.CheckpointFormatVersion||(n.CheckpointFormatVersion={}))})(Wy||(Wy={}));/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============================================================================= + */var Gy;(function(n){n[n.FAIL=0]="FAIL",n[n.SHORTEST=1]="SHORTEST",n[n.LONGEST=2]="LONGEST"})(Gy||(Gy={}));/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nt(n,e){Array.isArray(n)||(n=[n]),n.forEach(t=>{t!=null&&N(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the CPU backend.`)})}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const oF=c4;class qm extends b0{nextDataId(){return qm.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new t2(this,Tr())}write(e,t,s){this.firstUse&&(this.firstUse=!1,oe().get("IS_NODE")&&Ir(` +============================ +Hi, 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. +============================`));const r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:s,refCount:1}),r}makeTensorInfo(e,t,s){let r;if(t==="string"&&s!=null&&s.length>0&&Kc(s[0])){const i=s.map(o=>_o(o));r=this.write(i,e,t)}else r=this.write(s,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){const t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){const t=this.data.get(e);t.refCount--}}move(e,t,s,r,i){this.data.set(e,{values:t,dtype:r,refCount:i})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:s}=this.data.get(e);if(t==="complex64"){const r=this.readSync(s.real.dataId),i=this.readSync(s.imag.dataId);return _i(r,i)}return Sf(this.data.get(e).values,t)}bufferSync(e){const t=this.readSync(e.dataId);if(e.dtype==="string")try{const s=t.map(r=>Ci(r));return Tt(e.shape,e.dtype,s)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return Tt(e.shape,e.dtype,t)}makeOutput(e,t,s){return Tr().makeTensorFromTensorInfo(this.makeTensorInfo(t,s,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:s}=this.data.get(e);s!=null&&(this.disposeData(s.real.dataId,!0),this.disposeData(s.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=qs();return e(),{kernelMs:qs()-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){nt([e],"where");const t=this.readSync(e.dataId);return oF(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}qm.nextDataId=0;/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lI(n){const e=new Float32Array(n.length);for(let t=0;t{const{x:e}=n.inputs,t=n.backend;nt(e,"abs");let s=new Float32Array(re(e.shape));const r=t.data.get(e.dataId).values;return s=lI(r),t.makeOutput(s,e.shape,e.dtype)},lF={kernelName:td,backendName:"cpu",kernelFunc:aF};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Hn(n){return(e,t,s,r,i)=>{const o=pt(e,t),a=o.length,l=it(o),c=re(o),u=hs(i,c),h=e.length,d=t.length,p=it(e),f=it(t),x=oa(e,o),m=oa(t,o);if(x.length+m.length===0)for(let g=0;gb[T]=0);const y=Gi(b,h,p),w=v.slice(-d);m.forEach(T=>w[T]=0);const C=Gi(w,d,f);u[g]=n(s[y],r[C])}return[u,o]}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pr(n){const{inputs:e,backend:t}=n,{real:s,imag:r}=e,i=t.data.get(s.dataId).values,o=t.data.get(r.dataId).values,a=t.makeTensorInfo(s.shape,"complex64"),l=t.data.get(a.dataId);return l.complexTensorInfos={real:t.makeTensorInfo(s.shape,"float32",i),imag:t.makeTensorInfo(r.shape,"float32",o)},a}const cF={kernelName:E0,backendName:"cpu",kernelFunc:pr};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jf(n,e,t="float32"){if(t==="complex64"){const r=jf(n,e,"float32"),i=jf(n,e,"float32");return pr({inputs:{real:r,imag:i},backend:n})}const s=Cs(re(e),t);return n.makeTensorInfo(e,t,s)}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function eo(n){const{inputs:e,backend:t}=n,{x:s}=e;return t.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const uF={kernelName:gu,backendName:"cpu",kernelFunc:eo};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Sl(n){const{inputs:e,backend:t}=n,{input:s}=e,r=t.data.get(s.dataId).complexTensorInfos.real,i=t.data.get(r.dataId).values;return t.makeTensorInfo(r.shape,r.dtype,i)}const hF={kernelName:Y0,backendName:"cpu",kernelFunc:Sl};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cI(n,e,t,s){if(s==="int32"){const r=Int32Array.from(n);return[e,"int32",r]}if(s==="bool"){const r=Rl([0],t),[i,o]=Hn((a,l)=>a!==l?1:0)(e,[],n,r,"bool");return[o,"bool",i]}throw new Error(`Error in Cast: failed to cast ${t} to ${s}`)}function da(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{dtype:i}=s;if(i==="complex64"){if(r.dtype==="complex64")return eo({inputs:{x:r},backend:t});const u=jf(t,r.shape,r.dtype),h=da({inputs:{x:r},backend:t,attrs:{dtype:"float32"}}),d=pr({inputs:{real:h,imag:u},backend:t});return t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(h),d}if(r.dtype==="complex64"){const u=Sl({inputs:{input:r},backend:t}),h=da({inputs:{x:u},backend:t,attrs:{dtype:i}});return t.disposeIntermediateTensorInfo(u),h}if(!i2(r.dtype,i)){const u=eo({inputs:{x:r},backend:t});return{dataId:u.dataId,shape:u.shape,dtype:i}}const o=t.data.get(r.dataId).values,[a,l,c]=cI(o,r.shape,r.dtype,i);return t.makeTensorInfo(a,l,c)}const dF={kernelName:su,backendName:"cpu",kernelFunc:da};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function is(n,e,t,s){return t==null?({inputs:r,backend:i})=>{const{a:o,b:a}=r,l=i;nt([o,a],n);const c=l.data.get(o.dataId).values,u=l.data.get(a.dataId).values,h=o.dtype==="string"?Ti(c):c,d=o.dtype==="string"?Ti(u):u,p=s||o.dtype,[f,x]=e(o.shape,a.shape,h,d,p);return l.makeTensorInfo(x,p,f)}:({inputs:r,backend:i})=>{const{a:o,b:a}=r,l=i;if(o.dtype==="complex64"||a.dtype==="complex64"){const c=da({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),u=l.data.get(c.dataId),h=u.complexTensorInfos.real,d=u.complexTensorInfos.imag,p=l.data.get(h.dataId).values,f=l.data.get(d.dataId).values,x=da({inputs:{x:a},backend:l,attrs:{dtype:"complex64"}}),m=l.data.get(x.dataId),g=m.complexTensorInfos.real,v=m.complexTensorInfos.imag,b=l.data.get(g.dataId).values,y=l.data.get(v.dataId).values,[w,C,T]=t(o.shape,a.shape,p,f,b,y),E=l.makeTensorInfo(T,"float32",w),R=l.makeTensorInfo(T,"float32",C),_=pr({inputs:{real:E,imag:R},backend:l});return l.disposeIntermediateTensorInfo(c),l.disposeIntermediateTensorInfo(x),l.disposeIntermediateTensorInfo(E),l.disposeIntermediateTensorInfo(R),_}else{const c=l.data.get(o.dataId).values,u=l.data.get(a.dataId).values,h=s||o.dtype,[d,p]=e(o.shape,a.shape,c,u,h);return l.makeTensorInfo(p,h,d)}}}function zv(n){return(e,t,s,r,i,o)=>{const a=pt(e,t),l=re(a),c=a.length,u=it(a),h=hs("float32",l),d=hs("float32",l),p=oa(e,a),f=oa(t,a),x=_i(s,r),m=_i(i,o),g=e.length,v=it(e),b=t.length,y=it(t);if(p.length+f.length===0)for(let w=0;wT[F]=0);const E=Gi(T,g,v),R=C.slice(-b);f.forEach(F=>R[F]=0);const _=Gi(R,b,y),k=n(x[E*2],x[E*2+1],m[_*2],m[_*2+1]);h[w]=k.real,d[w]=k.imag}return[h,d,a]}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uI=Hn((n,e)=>n+e),pF=zv((n,e,t,s)=>({real:n+t,imag:e+s})),Pc=is(El,uI,pF),fF={kernelName:El,backendName:"cpu",kernelFunc:Pc};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Bv(n,e,t,s,r){const i=re(s),o=Cs(r,t);for(let a=0;a=r||(i>0?o[l]+=e[a]:o[l]+=1)}return o}function hI(n,e,t,s=!1){const r=n.shape[0],i=n.shape[1],o=Tt([r,t],e.dtype);for(let a=0;a=t||(s?o.set(1,a,c):e.size>0?o.set(o.get(a,c)+e.get(a,l),a,c):o.set(o.get(a,c)+1,a,c))}return o}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dI=Hn((n,e)=>n&e),mF=is(c2,dI),gF={kernelName:c2,backendName:"cpu",kernelFunc:mF};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ro(n){return(e,t,s)=>{const r=Pn(t,e.length);for(let i=0;i{const{x:o}=s;nt(o,n);const a=i,l=a.data.get(o.dataId).values;let c;if(o.dtype==="string"){if(!Array.isArray(l))throw new Error("String tensor's value was not an instance of Array");c=Ti(l)}else c=l;const u=t||o.dtype,h=e(c,u,r);return a.makeTensorInfo(o.shape,u,h)}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pI=ro(n=>Math.ceil(n)),xF=Ea(ru,pI),vF={kernelName:ru,backendName:"cpu",kernelFunc:xF};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fI(n,e,t,s){const r=Pn(t,re(e));if(s&&t!=="string"){let i=0;n.forEach(o=>{const a=re(o.shape);r.set(o.vals,i),i+=a})}else{let i=0;n.forEach(o=>{const a=t==="string"?Ti(o.vals):o.vals;let l=0;for(let c=0;cn===e?1:0),gI=is(gd,mI,null,"bool"),bF={kernelName:gd,backendName:"cpu",kernelFunc:gI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xI=ro(n=>Math.exp(n)),vI=Ea(hu,xI,"float32"),yF={kernelName:hu,backendName:"cpu",kernelFunc:vI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bI=ro(n=>Math.expm1(n)),wF=Ea(du,bI),SF={kernelName:du,backendName:"cpu",kernelFunc:wF};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yI=ro(n=>Math.floor(n)),CF=Ea(pu,yI),_F={kernelName:pu,backendName:"cpu",kernelFunc:CF};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wI=Hn((n,e)=>Math.floor(n/e)),TF=is(fu,wI,null,"int32"),IF={kernelName:fu,backendName:"cpu",kernelFunc:TF};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function SI(n,e,t,s,r,i,o,a,l){const c=Tt([s,i],t);for(let u=0;u=l/i)throw new Error(`Invalid indices: ${h} does not index into ${a}`);for(let p=0;pn>e?1:0),EF=is(yd,_I,null,"bool"),kF={kernelName:yd,backendName:"cpu",kernelFunc:EF};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const TI=Hn((n,e)=>n>=e?1:0),AF=is(mu,TI,null,"bool"),RF={kernelName:mu,backendName:"cpu",kernelFunc:AF};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const II=Hn((n,e)=>nn<=e?1:0),$F=is(Cd,EI,null,"bool"),DF={kernelName:Cd,backendName:"cpu",kernelFunc:$F};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kI(n,e,t){const s=(e-n)/(t-1),r=Cs(t,"float32");r[0]=n;for(let i=1;iMath.log(n)),PF=Ea(yu,AI),LF={kernelName:yu,backendName:"cpu",kernelFunc:PF};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function RI(n,e,t,s){const r=hs(s,re(t));for(let i=0;ia)&&(a=c)}r[i]=a}return r}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const MI=Hn((n,e)=>Math.max(n,e)),FF=is(Su,MI),OF={kernelName:Su,backendName:"cpu",kernelFunc:FF};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const NI=Hn((n,e)=>Math.min(n,e)),zF=is(Cu,NI),BF={kernelName:Cu,backendName:"cpu",kernelFunc:zF};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Uv=Hn((n,e)=>n*e),UF=zv((n,e,t,s)=>({real:n*t-e*s,imag:n*s+e*t})),Xm=is(Tu,Uv,UF),VF={kernelName:Tu,backendName:"cpu",kernelFunc:Xm};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $I(n,e,t){const s=ya(-1,t);return Uv([],e,s,n,t)}function WF(n){const{inputs:e,backend:t}=n,{x:s}=e;nt(s,"neg");const r=t.data.get(s.dataId).values,[i,o]=$I(r,s.shape,s.dtype);return t.makeTensorInfo(o,s.dtype,i)}const GF={kernelName:Dd,backendName:"cpu",kernelFunc:WF};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const DI=Hn((n,e)=>n!==e?1:0),HF=is(Pd,DI,null,"bool"),qF={kernelName:Pd,backendName:"cpu",kernelFunc:HF};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Vv(n,e,t,s,r){const i=e.length,o=re(e),a=it(e),l=it(r),c=hs(t,re(r));for(let u=0;ut.disposeIntermediateTensorInfo(v)),t.makeTensorInfo(g,m,f)}const jF={kernelName:Ud,backendName:"cpu",kernelFunc:KF};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function YF(n,e,t){n.forEach((s,r)=>{if(s<0||s>=t){const i=jc(r,e.length,it(e)).join(",");throw new Error(`indices[${i}] = ${s} is not in [0, ${t})`)}})}function ZF(n,e){for(let t=0;tr)throw new Error("Ragged splits must not point past values");for(let i=1;is[i])throw new Error("Ragged splits must be sorted in ascending order")}}function JF(n,e,t,s){const r=[];let i=0;const o=e.length-1+t.length,a=new Array(o).fill(null).map(()=>[0]);ZF(t,s);let l=1;for(let c=0;c=0){const x=a[f],m=x[x.length-1]-p[u];for(let g=u;gr[o]=i)}return e}function Hy(n,e){const t=n.slice(0,e);for(;t.length1)throw new Error("starts must be a scalar or vector");if(r.length>1)throw new Error("limits must be a scalar or vector");if(o.length>1)throw new Error("deltas must be a scalar or vector");const a=e.length===0,l=r.length===0,c=o.length===0,u=[];a||u.push(e[0]),l||u.push(r[0]),c||u.push(o[0]);for(let m=1;m0&&vg)y=0;else if(y=Math.ceil(Math.abs((v-g)/b)),y>qy)throw new Error(`Requires ((limit - start) / delta) <= ${qy}`);d[m+1]=d[m]+y}const p=d[h],f=Pn(t,p);let x=0;for(let m=0;ms&&(s=i)}return s}static getMaxWidthValueRowID(e){const t=e.length;if(t===0)return 0;let s=0,r=e[0],i=0;for(let o=1;o"Final length of result must be equal to firstDimension."),i}calculateOutputIndexRowSplit(e,t,s,r){const i=e.length,o=[];for(let a=0;a0&&o.length!==e[i-1])throw new Error("Invalid row split size.");return o}calculateOutputIndexValueRowID(e,t,s,r){const i=e.length,o=[];if(i===0)return[];let a=0,l=e[0];if(l>=t.length)throw new Error(`Got currentValueRowId=${l}, which is not less than ${t.length}`);let c=t[l];o.push(c);for(let u=1;u=0&&(++a,a=t.length)throw new Error(`Got nextValueRowId=${h} which is not less than ${t.length}`);c=t[h]}o.push(c)}if(o.length!==e.length)throw new Error("Invalid row ids.");return o}calculateOutputIndex(e,t,s,r){const i=this.getRowPartitionTensor(e),o=this.getRowPartitionTypeByDimension(e);switch(o){case Vr.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(i,t,s,r);case Vr.ROW_SPLITS:if(i.length-1>t.length)throw new Error(`Row partition size is greater than output size: ${i.length-1} > ${t.length}`);return this.calculateOutputIndexRowSplit(i,t,s,r);default:throw new Error(`Unsupported partition type: ${Vr[o]}`)}}getFirstDimensionSize(){const e=this.rowPartitionValues[0];if(this.rowPartitionTypes.length===0)throw new Error("No row_partition_types given.");const t=this.rowPartitionTypes[0];switch(t){case Vr.FIRST_DIM_SIZE:return e[0];case Vr.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case Vr.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${Vr[t]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");const t=this.getFirstDimensionSize(),s=this.calculateOutputSize(t),r=new Array(this.raggedRank+1);r[r.length-1]=1;for(let l=r.length-2;l>=0;--l)r[l]=r[l+1]*s[l+1];const i=Ky(s,!1),o=Pn(this.valuesDType,re(i));if(r[0]*s[0]>0){let l=this.calculateFirstParentOutputIndex(t,r[0],s[0]);for(let c=1;c<=this.raggedRank;++c)l=this.calculateOutputIndex(c-1,l,r[c],s[c]);this.setOutput(this.raggedRank,l,o,i)}return[i,o]}setOutput(e,t,s,r){if(s.length===0)return;const i=this.values,o=s;let a=r.slice();a=a.slice(e+1);const l=re(a),c=t.length;let u=this.defaultValue;if(u.length!==l&&u.length!==1){const f=this.defaultValueShape;le(()=>{const x=se(u,f);u=Mh(x,a).dataSync()})}let h=0,d=0,p=0;for(let f=0;f<=c;++f){let x=f=c){const m=s.length;x=Math.floor(m/l)}if(x>p)if(this.defaultValue.length===1)o.subarray(p*l,x*l).fill(this.defaultValue[0]),p=x;else for(;x>p;){const m=o.slice(p*l);Xy(m,u,l),++p}x<0?(h=f+1,d=p):(h=f,d=p,p=d+1)}}}function Xy(n,e,t){for(let s=0;s= 0`);if(s<-1)throw new Error(`Dimension ${s} must be >= -1`);s=-1}t.push(s)}return t}function OI(n,e,t,s,r,i,o,a,l,c){return new Yf(n,e,t,s,r,i,o,a,l,c).compute()}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zI(n,e,t,s){const r=n===e,i=n1;if(r||i||o)return Cs(0,s);const a=Math.abs(Math.ceil((e-n)/t)),l=Cs(a,s);e1/Math.sqrt(n)),nO=Ea(Mu,BI),sO={kernelName:Mu,backendName:"cpu",kernelFunc:nO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nl(n,e,t,s,r,i,o,a,l,c){const u=[s/r,r],h=n.values,d=e.values;if(s===0)return Tt(t,e.dtype);const p=l instanceof Ss?l:Tt(u,e.dtype);typeof l=="string"||typeof l=="number"?p.values.fill(l):typeof l=="boolean"&&p.values.fill(+l);for(let f=0;f=s/r)throw new Error(`Invalid indices: ${x} does not index into ${t}`);for(let g=0;g1/(1+Math.exp(-n))),UI=sn(Lu,n=>1/(1+Math.exp(-n))),iO={kernelName:Lu,backendName:"cpu",kernelFunc:UI};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function VI(n,e,t,s,r){const i=b4(s,e,t),o=re(t),a=it(s);if(i){const h=y4(e,a);return r==="string"?n.slice(h,h+o):n.subarray(h,h+o)}const l=r==="string"?Ti(n):n,c=Tt(s,r,l),u=Tt(t,r);for(let h=0;hf+e[x]);u.set(c.get(...p),...d)}return r==="string"?G4(u.values):u.values}function Cl(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{begin:i,size:o}=s;nt(r,"slice");const[a,l]=vm(r,i,o);hv(r,a,l);const c=t.data.get(r.dataId).values,u=VI(c,a,l,r.shape,r.dtype);return t.makeTensorInfo(l,r.dtype,u)}const oO={kernelName:Xd,backendName:"cpu",kernelFunc:Cl};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function WI(n,e,t,s,r,i,o){const a=e[0],l=i[0],c=new Array(l),u=new Array(a),h=e[1];if(l===0){if(a!==0)throw new Error(N4(a));const m=Pn(t,0),g=Pn(r,0);return[m,[0,h],g,c,u]}let d=!0,p=0;const f=new Array(l).fill(0);for(let m=0;m=l)throw new Error(D4(m,g,l));++f[g],d=d&&g>=p,p=g}let x=!0;for(let m=0;m0&&(f[m]+=f[m-1])}if(x&&d){const m=n,g=s;for(let v=0;v0){p[d-1]=1;for(let m=d-2;m>=0;--m)p[m]=p[m+1]*s[m+1]}const f=[];if(a>0){f[a-1]=1;for(let m=a-2;m>=0;--m)f[m]=f[m+1]*l[m+1]}const x=Pn(t,o*a);for(let m=0;m0?r[a-1]+1:0;if(h<0)throw new Error(ux());const d=e.slice();d[0]=h;const p=d.reduce((b,y)=>b*y,1),f=Pn(t,p);if(a===0)return h>0&&f.fill(o),[f,d];if(h<=0)throw new Error(ux());let x=0,m=1,g=0,v=r[x];for(;;){let b=0;if(m=b)throw new Error(B4())}if(v<0||v>=h)throw new Error(U4(v,h));v>g&&f.fill(o,g*c,v*c);for(let y=x;y=l[0])throw new Error(V4(y,s[y],l[0]));for(let C=0;Ca)break}return gMath.sqrt(n)),lO=sn(Ou,n=>Math.sqrt(n)),cO={kernelName:Ou,backendName:"cpu",kernelFunc:lO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const HI=Hn((n,e)=>{const t=n-e;return t*t}),uO=is(zu,HI),hO={kernelName:zu,backendName:"cpu",kernelFunc:uO};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qI=ro((n,e)=>{const{pattern:t,replaceGlobal:s,rewrite:r}=e;return n.replace(new RegExp(t,s?"g":""),r)}),dO=Ea(C2,qI),pO={kernelName:C2,backendName:"cpu",kernelFunc:dO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function XI(n,e,t,s){const r=Tt(n,e.dtype);for(let i=0;i0?0:a-l);let p=0;p+=c*this.leftPad.length;for(let v=0;vv.forEach(b=>x[m++]=b);for(let v=0;v0){g(e[d+h-1]);for(let v=0;v0){let l=t[0];if(l!==0)throw new Error(`First split value must be 0, got ${l}`);for(let c=1;c=l;if(u=u&&t[c]<=s,!u)throw new Error(`Invalid split value ${t[c]}, must be in [${l}, ${s}]`);l=t[c]}if(l!==s)throw new Error(`Last split value must be data size. Expected ${s}, got ${l}`)}const i=r-1,o=Pn("int32",r);if(s===0||r===0){const l=new Array(s);for(let c=0;c<=i;++c)o[c]=0;return[l,o]}o[0]=0;for(let l=1;l<=i;++l){const c=t[l]-t[l-1];let u=0;this.nGramWidths.forEach(h=>{u+=this.getNumNGrams(c,h)}),this.preserveShort&&c>0&&u===0&&(u=1),o[l]=o[l-1]+u}const a=new Array(o[i]);for(let l=0;l{const d=t[l+1]-t[l],p=this.getNumNGrams(d,h);this.createNGrams(e,c,a,u,p,h),u+=p}),this.preserveShort&&u===o[l]){const h=t[l+1]-t[l];if(h===0)continue;const d=h+2*this.padWidth;this.createNGrams(e,c,a,u,1,d)}}return[a,o]}}function KI(n,e,t,s,r,i,o,a){return new fO(t,s,r,i,o,a).compute(n,e)}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mO(n,e,t,s){if(!n.length)return;if(e.length===0){for(let i=0;in-e),gO=zv((n,e,t,s)=>({real:n-t,imag:e-s})),Gv=is(Bu,ZI,gO),xO={kernelName:Bu,backendName:"cpu",kernelFunc:Gv};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function JI(n,e){const t=new Array(n.rank);for(let r=0;r{const t=e.value-n.value;return t===0?n.index-e.index:t};function QI(n,e,t=0,s=n.length-1){for(;s>t;){if(s-t>600){const a=s-t+1,l=e-t+1,c=Math.log(a),u=.5*Math.exp(2*c/3),h=.5*Math.sqrt(c*u*(a-u)/a)*Math.sign(l-a/2),d=Math.max(t,Math.floor(e-l*u/a+h)),p=Math.min(s,Math.floor(e+(a-l)*u/a+h));QI(n,e,d,p)}const r=n[e];let i=t,o=s;for(fc(n,t,e),Ih(n[s],r)>0&&fc(n,t,s);i0;)o=o-1}Ih(n[t],r)===0?fc(n,t,o):(o=o+1,fc(n,o,s)),o<=e&&(t=o+1),e<=o&&(s=o-1)}}function eE(n,e,t,s,r){const i=e[e.length-1],[o,a]=[n.length/i,i],l=hs(t,o*s),c=hs("int32",o*s);for(let h=0;hf[b]={value:v,index:b}),s{for(let m=0;mnew qm,1);/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const sE=sn(cu,n=>n>=0?n:Math.exp(n)-1),vO={kernelName:cu,backendName:"cpu",kernelFunc:sE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rE(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{alpha:i}=s;nt([r],"leakyRelu");const o=re(r.shape),a=t.data.get(r.dataId).values,l=hs("float32",o);for(let c=0;cn<0?e*n:n);function iE(n){const{inputs:e,backend:t}=n,{x:s,alpha:r}=e;nt([s,r],"prelu");const i=t.data.get(s.dataId).values,o=t.data.get(r.dataId).values,[a,l]=yO(s.shape,r.shape,i,o,"float32");return t.makeTensorInfo(l,"float32",a)}const wO={kernelName:Bd,backendName:"cpu",kernelFunc:iE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const oE=sn(ku,n=>Math.max(0,n)),SO={kernelName:ku,backendName:"cpu",kernelFunc:oE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const aE=sn(Au,n=>Math.min(Math.max(0,n),6)),CO={kernelName:Au,backendName:"cpu",kernelFunc:aE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Zf(n,e,t,s,r){if(t==="linear")return eo({inputs:{x:e},backend:n});if(t==="relu")return oE({inputs:{x:e},backend:n});if(t==="elu")return sE({inputs:{x:e},backend:n});if(t==="relu6")return aE({inputs:{x:e},backend:n});if(t==="prelu")return iE({inputs:{x:e,alpha:s},backend:n});if(t==="leakyrelu")return rE({inputs:{x:e},backend:n,attrs:{alpha:r}});if(t==="sigmoid")return UI({inputs:{x:e},backend:n});throw new Error(`Activation ${t} has not been implemented for the CPU backend.`)}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gn(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{shape:i}=s,o=re(r.shape),a=r2(i,o),l=re(a);N(o===l,()=>`The new shape (${a}) has ${l} elements and the old shape (${r.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`),t.incRef(r.dataId);const c=t.data.get(r.dataId);if(c.complexTensorInfos!=null){const u=c.complexTensorInfos.real,h=c.complexTensorInfos.imag;u.shape=a,h.shape=a}return{dataId:r.dataId,shape:a,dtype:r.dtype}}const _O={kernelName:Vd,backendName:"cpu",kernelFunc:gn};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lE(n){const{inputs:e,backend:t,attrs:s}=n,{a:r,b:i}=e,{transposeA:o,transposeB:a}=s;nt([r,i],"matMul");const l=r.shape.length,c=i.shape.length,u=o?r.shape[l-2]:r.shape[l-1],h=a?i.shape[c-1]:i.shape[c-2],d=o?r.shape[l-1]:r.shape[l-2],p=a?i.shape[c-2]:i.shape[c-1],f=r.shape.slice(0,-2),x=i.shape.slice(0,-2),m=re(f),g=re(x),b=pt(r.shape.slice(0,-2),i.shape.slice(0,-2)).concat([d,p]);N(u===h,()=>`Error in matMul: inner shapes (${u}) and (${h}) of Tensors with shapes ${r.shape} and ${i.shape} and transposeA=${o} and transposeB=${a} must match.`);const y=o?[m,u,d]:[m,d,u],w=a?[g,p,h]:[g,h,p],C=gn({inputs:{x:r},backend:t,attrs:{shape:y}}),T=gn({inputs:{x:i},backend:t,attrs:{shape:w}}),E=o?C.shape[1]:C.shape[2],R=o?C.shape[2]:C.shape[1],_=a?T.shape[1]:T.shape[2],k=Math.max(m,g),F=t.data.get(C.dataId).values,B=t.data.get(T.dataId).values,M=it(C.shape),P=it(T.shape),[L,q,U]=o?[M[0],1,M[1]]:[M[0],M[1],1],[X,K,J]=a?[1,P[1],P[0]]:[P[1],1,P[0]],ae=R*_,he=Tt([k,R,_],C.dtype),j=he.values,ne=t.blockSize;for(let ge=0;geMath.acos(n)),AO={kernelName:Yc,backendName:"cpu",kernelFunc:kO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const RO=sn(Zc,n=>Math.acosh(n)),MO={kernelName:Zc,backendName:"cpu",kernelFunc:RO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function NO(n){const{inputs:e,backend:t}=n,s=e;nt(e,"addN");const r=s.map(a=>t.data.get(a.dataId).values),i=Tt(s[0].shape,s[0].dtype),o=i.values;for(let a=0;av&&(v=w,b=y)}p[m]=b}return c.forEach(m=>t.disposeIntermediateTensorInfo(m)),t.makeTensorInfo(u,"int32",p)}const zO={kernelName:nd,backendName:"cpu",kernelFunc:OO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function BO(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i}=s;nt(r,"argMin");let o=It(i,r.shape);const a=ln(o,r.shape.length);let l=r;const c=[];a!=null&&(l=ir({inputs:{x:r},backend:t,attrs:{perm:a}}),c.push(l),o=xn(o.length,l.shape.length)),o=[o[0]],Kn("argMin",o,l.shape.length);const[u,h]=Wn(l.shape,o),d=re(u),p=Cs(d,"int32"),f=re(h),x=t.data.get(l.dataId).values;for(let m=0;mt.disposeIntermediateTensorInfo(m)),t.makeTensorInfo(u,"int32",p)}const UO={kernelName:sd,backendName:"cpu",kernelFunc:BO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const VO=sn(Jc,n=>Math.asin(n)),WO={kernelName:Jc,backendName:"cpu",kernelFunc:VO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const GO=sn(Qc,n=>Math.asinh(n)),HO={kernelName:Qc,backendName:"cpu",kernelFunc:GO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qO=sn(eu,n=>Math.atan(n)),XO={kernelName:eu,backendName:"cpu",kernelFunc:qO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const KO=Hn((n,e)=>Math.atan2(n,e)),jO=is(nu,KO),YO={kernelName:nu,backendName:"cpu",kernelFunc:jO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ZO=sn(tu,n=>Math.atanh(n)),JO={kernelName:tu,backendName:"cpu",kernelFunc:ZO};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Hv(n,e,t,s,r,i){const o=r.strideHeight,a=r.strideWidth,l=r.dilationHeight,c=r.dilationWidth,u=r.effectiveFilterHeight,h=r.effectiveFilterWidth,d=r.padInfo.top,p=r.padInfo.left,f=i==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=Tt(r.outShape,t),m=x.values,g=r.outShape[1]*r.outShape[2]*r.outShape[3],v=r.outShape[2]*r.outShape[3],b=r.outShape[3];for(let y=0;yq?q=ne:i==="avg"&&(U+=ne,X++)}if(isNaN(q))break}const K=F+B*b+T;m[K]=i==="avg"?U/X:q}}}return x}function cE(n,e,t,s,r=!1,i=!1){const o=Tt(s.outShape,"int32"),a=s.strideHeight,l=s.strideWidth,c=s.dilationHeight,u=s.dilationWidth,h=s.effectiveFilterHeight,d=s.effectiveFilterWidth,p=s.padInfo.top,f=s.padInfo.left,x=Tt(e,t,n);for(let m=0;m_&&(_=L,r?k=i?((m*s.inHeight+F)*s.inWidth+M)*s.inChannels+g:(F*s.inWidth+M)*s.inChannels+g:k=B*d+P)}}o.set(k,m,v,C,g)}}return o}function uE(n,e,t,s,r,i){const o=r.strideDepth,a=r.strideHeight,l=r.strideWidth,c=r.dilationDepth,u=r.dilationHeight,h=r.dilationWidth,d=r.effectiveFilterDepth,p=r.effectiveFilterHeight,f=r.effectiveFilterWidth,x=r.padInfo.front,m=r.padInfo.top,g=r.padInfo.left,v=i==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,b=Tt(r.outShape,t),y=b.values,w=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],C=r.outShape[2]*r.outShape[3]*r.outShape[4],T=r.outShape[3]*r.outShape[4],E=r.outShape[4];for(let R=0;RTe?Te=Je:i==="avg"&&(ve+=Je,Ge++),isNaN(Te))break}if(isNaN(Te))break}if(isNaN(Te))break}const $e=be+F;y[$e]=i==="avg"?ve/Math.max(Ge,1):Te}}}}return b}function QO(n,e){const t=Tt(e.outShape,"int32"),s=e.strideDepth,r=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,a=e.dilationHeight,l=e.dilationWidth,c=e.effectiveFilterDepth,u=e.effectiveFilterHeight,h=e.effectiveFilterWidth,d=e.padInfo.front,p=e.padInfo.top,f=e.padInfo.left;for(let x=0;x=B&&(B=J,M=L*u*h+U*u+K)}}}t.set(M,x,g,w,R,m)}}}return t}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function e9(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e;nt(r,"avgPool");const{filterSize:i,strides:o,pad:a,dimRoundingMode:l}=s,c=1;N(gs(o,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const u=Rs(r.shape,i,o,c,a,l);let h;if(u.filterWidth===1&&u.filterHeight===1&&Wt(u.inShape,u.outShape))h=eo({inputs:{x:r},backend:t});else{const d=t.data.get(r.dataId).values,p=it(r.shape),f=Hv(d,r.shape,r.dtype,p,u,"avg");h=t.makeTensorInfo(u.outShape,r.dtype,f.values)}return h}const t9={kernelName:rd,backendName:"cpu",kernelFunc:e9};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function n9(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{filterSize:i,strides:o,pad:a,dimRoundingMode:l,dataFormat:c}=s;nt(r,"avgPool3d");const u=$r(r.shape,i,o,1,a,l,c),h=t.data.get(r.dataId).values,d=uE(h,r.shape,r.dtype,it(r.shape),u,"avg");return t.makeTensorInfo(d.shape,"float32",d.values)}const s9={kernelName:id,backendName:"cpu",kernelFunc:n9};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function r9(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:i}=e,{filterSize:o,strides:a,pad:l,dimRoundingMode:c}=s;nt([r,i],"avgPool3DGrad");const u=$r(i.shape,o,a,1,l,c),h=u.strideDepth,d=u.strideHeight,p=u.strideWidth,f=u.filterDepth,x=u.filterHeight,m=u.filterWidth,g=u.dilationDepth,v=u.dilationHeight,b=u.dilationWidth,y=u.effectiveFilterDepth,w=u.effectiveFilterHeight,C=u.effectiveFilterWidth,T=y-1-u.padInfo.front,E=C-1-u.padInfo.left,R=w-1-u.padInfo.top,_=Tt(i.shape,"float32"),k=1/(f*x*m),F=t.bufferSync(r);for(let B=0;B=u.outDepth||Math.floor(he)!==he))for(let j=0;j=u.outHeight||Math.floor(ne)!==ne))for(let ge=0;ge=u.outWidth||Math.floor(be)!==be)continue;const Te=F.get(B,he,ne,be,M);J+=Te}}}_.set(J*k,B,P,L,q,M)}return t.makeTensorInfo(_.shape,_.dtype,_.values)}const i9={kernelName:T0,backendName:"cpu",kernelFunc:r9};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function o9(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:i}=e,o=i;nt([r,i],"avgPoolGrad");const{filterSize:a,strides:l,pad:c}=s,u=Rs(o.shape,a,l,1,c),h=u.strideHeight,d=u.strideWidth,p=u.filterHeight,f=u.filterWidth,x=u.dilationHeight,m=u.dilationWidth,g=u.effectiveFilterHeight,v=u.effectiveFilterWidth,b=v-1-u.padInfo.left,y=g-1-u.padInfo.top,w=Tt(o.shape,"float32"),C=1/(p*f),T=t.data.get(r.dataId).values,E=Tt(r.shape,"float32",T);for(let R=0;R=u.outHeight||Math.floor(q)!==q))for(let U=0;U=u.outWidth||Math.floor(X)!==X)continue;const K=E.get(R,q,X,_);P+=K}}w.set(P*C,R,k,F,_)}return t.makeTensorInfo(w.shape,w.dtype,w.values)}const a9={kernelName:_0,backendName:"cpu",kernelFunc:o9};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function l9(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,scale:i,offset:o,mean:a,variance:l}=e;N(a.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),N(o==null||a.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),N(i==null||a.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),nt([r,a,l,i,o],"batchNorm");let{varianceEpsilon:c}=s;c==null&&(c=.001);const u=t.data.get(r.dataId).values,h=t.data.get(a.dataId).values,d=t.data.get(l.dataId).values,p=i?t.data.get(i.dataId).values:new Float32Array([1]),f=o?t.data.get(o.dataId).values:new Float32Array([0]),x=new Float32Array(u.length),m=f.length,g=p.length,v=d.length,b=h.length;let y=0,w=0,C=0,T=0;for(let E=0;E=m&&(y=0),w>=b&&(w=0),C>=g&&(C=0),T>=v&&(T=0);return t.makeTensorInfo(r.shape,r.dtype,x)}const c9={kernelName:vd,backendName:"cpu",kernelFunc:l9};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function u9(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{blockShape:i,crops:o}=s;nt([r],"batchToSpaceND");const a=i.reduce((g,v)=>g*v),l=Dl(r.shape,i,a),c=Pl(l.length,i.length),u=Ll(r.shape,i,a),h=Sm(o,i.length),d=Cm(u,o,i.length),p=gn({inputs:{x:r},backend:t,attrs:{shape:l}}),f=ir({inputs:{x:p},backend:t,attrs:{perm:c}}),x=gn({inputs:{x:f},backend:t,attrs:{shape:u}}),m=Cl({inputs:{x},backend:t,attrs:{begin:h,size:d}});return t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(x),m}const h9={kernelName:ad,backendName:"cpu",kernelFunc:u9};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function d9(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,weights:i}=e,{size:o}=s,a=t.data.get(r.dataId).values,l=t.data.get(i.dataId).values,c=Bv(a,l,i.dtype,i.shape,o);return t.makeTensorInfo([o],i.dtype,c)}const p9={kernelName:I0,backendName:"cpu",kernelFunc:d9};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function f9(n){const{inputs:e,backend:t}=n,{s0:s,s1:r}=e,i=t.data.get(s.dataId).values,o=t.data.get(r.dataId).values,a=pt(Array.from(i),Array.from(o));return t.makeTensorInfo([a.length],"int32",Int32Array.from(a))}const m9={kernelName:u2,backendName:"cpu",kernelFunc:f9};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const g9=sn(iu,(n,e)=>{const t=e;return n>t.clipValueMax?t.clipValueMax:n{const{x:e}=n.inputs,t=n.backend,s=new Float32Array(re(e.shape)),r=t.data.get(e.dataId),i=r.complexTensorInfos.real,o=r.complexTensorInfos.imag,a=t.data.get(i.dataId).values,l=t.data.get(o.dataId).values;for(let c=0;cx.shape);bm(o,i);let a=nr(e.map(x=>x.shape),i);if(re(a)===0)return t.makeTensorInfo(a,e[0].dtype,[]);const l=e.filter(x=>re(x.shape)>0);if(l.length===1)return eo({inputs:{x:l[0]},backend:t});if(l[0].dtype==="complex64"){const x=l.map(y=>Sl({inputs:{input:y},backend:t})),m=l.map(y=>Lc({inputs:{input:y},backend:t})),g=Fc({inputs:x,backend:t,attrs:{axis:i}}),v=Fc({inputs:m,backend:t,attrs:{axis:i}}),b=pr({inputs:{real:g,imag:v},backend:t});return x.forEach(y=>t.disposeIntermediateTensorInfo(y)),m.forEach(y=>t.disposeIntermediateTensorInfo(y)),t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(v),b}const c=l.map(x=>{const g=[-1,re(x.shape.slice(i))];return gn({inputs:{x},backend:t,attrs:{shape:g}})}),u=c.map(x=>({vals:t.data.get(x.dataId).values,shape:x.shape}));a=nr(c.map(x=>x.shape),1);const h=c[0].shape[0]===1,d=fI(u,a,e[0].dtype,h),p=nr(l.map(x=>x.shape),i),f=t.makeTensorInfo(p,e[0].dtype,d);return c.forEach(x=>t.disposeIntermediateTensorInfo(x)),f}const w9={kernelName:cd,backendName:"cpu",kernelFunc:Fc};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function hE(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:i}=e,{strides:o,pad:a,dataFormat:l,dilations:c,dimRoundingMode:u}=s;nt([r,i],"conv2d");const h=wr(l),d=Cn(r.shape,i.shape,o,c,a,u,!1,h),p=d.filterHeight,f=d.filterWidth,x=d.dilationHeight,m=d.dilationWidth,g=d.padInfo.left,v=d.padInfo.top,b=d.dataFormat==="channelsLast",y=new Ss(d.outShape,r.dtype),w=it(r.shape),C=it(i.shape),T=w[0],E=b?w[1]:w[2],R=b?w[2]:1,_=b?1:w[1],k=y.strides[0],F=b?y.strides[1]:y.strides[2],B=b?y.strides[2]:1,M=b?1:y.strides[1],P=t.data.get(r.dataId).values,L=t.data.get(i.dataId).values,q=y.values;for(let U=0;U=d.inHeight)continue;const ge=j*C[0],be=X+ne*E;for(let Te=0;Te=d.inWidth)continue;const mt=ge+$e*C[1],Ve=be+te*R;let Ke=mt;for(let Pe=0;Pe=c.inDepth)continue;const U=L*R[0],X=k+q*E[1];for(let K=0;K=c.inHeight)continue;const ne=U+he*R[1],ge=X+j*E[2];for(let be=0;be=c.inWidth)continue;const te=ne+Ge*R[2],mt=ge+$e*c.inChannels;let Ve=te;for(let Ke=0;KeMath.cos(n)),D9={kernelName:ou,backendName:"cpu",kernelFunc:$9};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const P9=sn(au,n=>Math.cosh(n)),L9={kernelName:au,backendName:"cpu",kernelFunc:P9};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function F9(n){const{inputs:e,backend:t,attrs:s}=n,{image:r,boxes:i,boxInd:o}=e,{cropSize:a,method:l,extrapolationValue:c}=s,[u,h,d,p]=r.shape,f=i.shape[0],[x,m]=a,g=Tt([f,x,m,p],"float32"),v=t.data.get(i.dataId).values,b=t.data.get(o.dataId).values,y=t.data.get(r.dataId).values,w=it(r.shape),C=it(g.shape);for(let T=0;T=u)continue;const M=x>1?(k-R)*(h-1)/(x-1):0,P=m>1?(F-_)*(d-1)/(m-1):0;for(let L=0;L1?R*(h-1)+L*M:.5*(R+k)*(h-1);if(q<0||q>h-1){for(let U=0;U1?_*(d-1)+J*P:.5*(_+F)*(d-1);if(ae<0||ae>d-1){for(let ge=0;ge1?_*(d-1)+U*P:.5*(_+F)*(d-1);if(X<0||X>d-1){for(let ae=0;aeg+f-v-1:(g,v)=>g+v;for(let g=0;gg+f-v-1:(g,v)=>g+v;for(let g=0;g`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${o}`);const a=r.shape[0],l=r.shape[1],c=r.shape[2],u=r.shape[3],h=l*i,d=c*i,p=u/(i*i),f=t.data.get(r.dataId).values,x=new Float32Array(a*h*d*p);let m=0;for(let g=0;g`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${d}'`);const p=Cn(r.shape,i.shape,o,d,a,c,!0),{filterHeight:f,filterWidth:x,dilationHeight:m,dilationWidth:g,padInfo:v}=p,b=v.left,y=v.top,w=p.outChannels/p.inChannels,C=new Ss(p.outShape,r.dtype),T=t.data.get(r.dataId).values,E=t.data.get(i.dataId).values,R=C.values;for(let _=0;_=p.inHeight)continue;const U=L*h[0],X=k+q*u[1];for(let K=0;K=p.inWidth)continue;const ne=U+he*h[1],ge=X+j*p.inChannels;let be=J,Te=ne;for(let ve=0;ve{const{x:s,filter:r}=n,{strides:i,pad:o,dilations:a}=t,l=e,c=l.data.get(s.dataId).values,u=s.shape.length,h=l.data.get(r.dataId).values,d=r.shape.length,{batchSize:p,inHeight:f,inWidth:x,inChannels:m,outHeight:g,outWidth:v,padInfo:b,strideHeight:y,strideWidth:w,filterHeight:C,filterWidth:T,dilationHeight:E,dilationWidth:R,outShape:_}=Sa(s.shape,r.shape,i,o,"NHWC",a),k=re(_),F=_.length,B=Pn(s.dtype,k);for(let P=0;P=0&&j=0&&geJ&&(J=ve)}}}const ae=Gi([P,L,U,K],F,it(_));B[ae]=J}}}return{dataId:l.write(Rl(B,s.dtype),_,s.dtype),shape:_,dtype:s.dtype}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tz={kernelName:Mf,backendName:"cpu",kernelFunc:({inputs:n,backend:e,attrs:t})=>{const{x:s,filter:r,dy:i}=n,{strides:o,pad:a,dilations:l}=t,c=e,u=yi(s.shape,c.data.get(s.dataId).values),h=yi(r.shape,c.data.get(r.dataId).values),{batchSize:d,inHeight:p,inWidth:f,inChannels:x,outHeight:m,outWidth:g,padInfo:v,strideHeight:b,strideWidth:y,filterHeight:w,filterWidth:C,dilationHeight:T,dilationWidth:E,outShape:R}=Sa(s.shape,r.shape,o,a,"NHWC",l);N(i.rank===R.length,()=>`Error in ${Mf}, dy must have the same rank as output ${R.length}, but got ${i.rank}`);const _=yi(R,c.data.get(i.dataId).values),k=jS(r.shape,r.dtype);for(let B=0;B=0&&he=0&&neX&&(X=ge,K=ae,J=j)}}}k[K][J][U]+=_[B][M][L][U]}}}return{dataId:c.write(Rl(k,s.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nz={kernelName:Rf,backendName:"cpu",kernelFunc:({inputs:n,backend:e,attrs:t})=>{const{x:s,filter:r,dy:i}=n,{strides:o,pad:a,dilations:l}=t,c=e,u=yi(s.shape,c.data.get(s.dataId).values),h=yi(r.shape,c.data.get(r.dataId).values),{batchSize:d,inHeight:p,inWidth:f,inChannels:x,outHeight:m,outWidth:g,padInfo:v,strideHeight:b,strideWidth:y,filterHeight:w,filterWidth:C,dilationHeight:T,dilationWidth:E,outShape:R}=Sa(s.shape,r.shape,o,a,"NHWC",l);N(i.rank===R.length,()=>`Error in ${Rf}, dy must have the same rank as output ${R.length}, but got ${i.rank}`);const _=yi(R,c.data.get(i.dataId).values),k=jS(s.shape,s.dtype);for(let B=0;B=0&&he=0&&neX&&(X=ge,K=he,J=ne)}}}k[B][K][J][U]+=_[B][M][L][U]}}}return{dataId:c.write(Rl(k,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sz(n){const{inputs:e,backend:t,attrs:s}=n,{image:r}=e,{canvas:i,options:o}=s,{contextOptions:a,imageOptions:l}=o||{},c=l?.alpha||1,u=a?.contextType||"2d";if(u!=="2d")throw new Error(`Context type ${a.contextType} is not supported by the CPU backend.`);const h=i.getContext(u,a?.contextAttributes||{});if(h==null)throw new Error(`Could not get the context with ${u} type.`);const[d,p]=r.shape.slice(0,2),f=r.shape.length===2?1:r.shape[2],x=t.data.get(r.dataId).values,m=r.dtype==="float32"?255:1,g=new Uint8ClampedArray(p*d*4);for(let b=0;b1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${T}.`)}else if(r.dtype==="int32"&&(T<0||T>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${T}.`);f===1?(y[0]=T*m,y[1]=T*m,y[2]=T*m):y[C]=T*m}const w=b*4;g[w+0]=Math.round(y[0]),g[w+1]=Math.round(y[1]),g[w+2]=Math.round(y[2]),g[w+3]=Math.round(y[3])}i.width=p,i.height=d;const v=new ImageData(g,p,d);return h.putImageData(v,0,0),r}const rz={kernelName:JS,backendName:"cpu",kernelFunc:sz};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mp(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i,keepDims:o}=s;nt(r,"sum");let a;r.dtype==="bool"?a=da({inputs:{x:r},backend:t,attrs:{dtype:"int32"}}):a=eo({inputs:{x:r},backend:t});const l=a.shape.length,c=It(i,a.shape),u=ln(c,l);let h=c,d=a;u!=null&&(d=ir({inputs:{x:a},backend:t,attrs:{perm:u}}),h=xn(h.length,l)),Kn("sum",h,d.shape.length);const[p,f]=Wn(d.shape,h),x=ds(d.dtype,"int32");let m=jf(t,p,x);const g=re(f),v=t.data.get(m.dataId).values,b=t.data.get(d.dataId).values;for(let y=0;y=0&&(d=mp({inputs:{x:d},backend:t,attrs:{axis:c[x]-(o.length-p),keepDims:!1}}),f.push(d)),p--)}for(const x of f)x!==d&&t.disposeIntermediateTensorInfo(x);return d}const az={kernelName:F0,backendName:"cpu",kernelFunc:oz};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lz(n){const{inputs:e,backend:t}=n,{dy:s,y:r}=e;nt([s,r],"eluGrad");const i=new Float32Array(re(r.shape)),o=t.data.get(r.dataId).values,a=t.data.get(s.dataId).values;for(let l=0;l=0?i[l]=a[l]:i[l]=a[l]*(c+1)}return t.makeTensorInfo(r.shape,"float32",i)}const cz={kernelName:O0,backendName:"cpu",kernelFunc:lz};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uz=_m,hz=Tm,dz=Im,pz=Em,fz=km,mz=Am,gz=sn(uu,n=>{const e=Math.sign(n),t=Math.abs(n),s=1/(1+uz*t);return e*(1-((((mz*s+fz)*s+pz)*s+dz)*s+hz)*s*Math.exp(-t*t))}),xz={kernelName:uu,backendName:"cpu",kernelFunc:gz};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Jf(n){const{inputs:e,backend:t,attrs:s}=n,{input:r}=e,{dim:i}=s,o=r.shape.length,a=r.shape.slice();let l=i;return i<0&&(N(-(o+1)<=i,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+i+1),a.splice(l,0,1),gn({inputs:{x:r},backend:t,attrs:{shape:a}})}const vz={kernelName:xd,backendName:"cpu",kernelFunc:Jf};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bz=Hn((n,e)=>n/e),qv=is(lu,bz),wx={kernelName:lu,backendName:"cpu",kernelFunc:qv};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pE(n,e,t){const s=n.shape,r=s[0],i=s[1],o=t.data.get(n.dataId),a=o.complexTensorInfos.real,l=o.complexTensorInfos.imag,c=[r,i],u=re(c),h=hs("float32",u),d=hs("float32",u);for(let m=0;m{const{image:s}=n,r=t,i=hs(s.dtype,re(s.shape)),[o,a,l,c]=s.shape,u=r.data.get(s.dataId).values;for(let d=0;d=0&&b=0,()=>`GatherV2: the index value ${w} is not in [0, ${u-1}]`)}let h=a;a==null&&(h=0);const d=re(i.shape),p=gv(r,i,l,h),f=gn({inputs:{x:r},backend:t,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),x=gn({inputs:{x:i},backend:t,attrs:{shape:[p.batchSize,d/p.batchSize]}}),m=[p.batchSize,p.outerSize,d/p.batchSize,p.sliceSize],g=t.bufferSync(x),v=t.bufferSync(f),b=CI(v,g,m);return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(x),t.makeTensorInfo(p.outputShape,b.dtype,b.values)}const Pz={kernelName:bd,backendName:"cpu",kernelFunc:Dz};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Lz(n){const{inputs:e,backend:t}=n,{input:s}=e,r=re(s.shape),i=s.shape[s.shape.length-1],o=r/i,a=gn({inputs:{x:s},backend:t,attrs:{shape:[o,i]}}),l=pE(a,!0,t),c=gn({inputs:{x:l},backend:t,attrs:{shape:s.shape}});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(l),c}const Fz={kernelName:V0,backendName:"cpu",kernelFunc:Lz};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Oz=sn(xu,n=>Number.isFinite(n)?1:0,"bool"),zz={kernelName:xu,backendName:"cpu",kernelFunc:Oz};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Bz=sn(vu,n=>Math.abs(n)===1/0?1:0,"bool"),Uz={kernelName:vu,backendName:"cpu",kernelFunc:Bz};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Vz=sn(bu,n=>Number.isNaN(n)?1:0,"bool"),Wz={kernelName:bu,backendName:"cpu",kernelFunc:Vz};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Gz(n){const{backend:e,attrs:t}=n,{start:s,stop:r,num:i}=t,o=kI(s,r,i);return e.makeTensorInfo([o.length],"float32",o)}const Hz={kernelName:p2,backendName:"cpu",kernelFunc:Gz};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qz=sn(wu,n=>Math.log1p(n)),Xz={kernelName:wu,backendName:"cpu",kernelFunc:qz};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Kz=Hn((n,e)=>n&&e),jz=is(_d,Kz,null,"bool"),Yz={kernelName:_d,backendName:"cpu",kernelFunc:jz};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Zz=sn(Td,n=>n?0:1,"bool"),Jz={kernelName:Td,backendName:"cpu",kernelFunc:Zz};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qz=Hn((n,e)=>n||e),eB=is(Id,Qz,null,"bool"),tB={kernelName:Id,backendName:"cpu",kernelFunc:eB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nB(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{depthRadius:i,bias:o,alpha:a,beta:l}=s;nt(r,"LRN");const c=r.shape[3],u=c-1,h=t.data.get(r.dataId).values,d=re(r.shape),p=new Float32Array(d);function f(x){const m=x%c;let g=x-m+Math.max(0,m-i);const v=x-m+Math.min(m+i,u);let b=0;for(;g<=v;g++){const y=h[g];b+=y*y}return b}for(let x=0;x`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const u=Rs(r.shape,i,o,c,a,l);let h;if(u.filterWidth===1&&u.filterHeight===1&&Wt(u.inShape,u.outShape))h=eo({inputs:{x:r},backend:t});else{const d=t.data.get(r.dataId).values,p=it(r.shape),f=Hv(d,r.shape,r.dtype,p,u,"max");h=t.makeTensorInfo(u.outShape,r.dtype,f.values)}return h}const lB={kernelName:Ad,backendName:"cpu",kernelFunc:aB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cB(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{filterSize:i,strides:o,pad:a,dimRoundingMode:l,dataFormat:c}=s;nt(r,"maxPool3d");const u=$r(r.shape,i,o,1,a,l,c),h=t.data.get(r.dataId).values,d=uE(h,r.shape,r.dtype,it(r.shape),u,"max");return t.makeTensorInfo(d.shape,"float32",d.values)}const uB={kernelName:Rd,backendName:"cpu",kernelFunc:cB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function hB(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:i}=e,{filterSize:o,strides:a,pad:l,dimRoundingMode:c}=s;nt([r,i],"maxPool3DGrad");const u=$r(i.shape,o,a,1,l,c),h=t.bufferSync(i),d=QO(h,u),p=u.strideDepth,f=u.strideHeight,x=u.strideWidth,m=u.dilationDepth,g=u.dilationHeight,v=u.dilationWidth,b=u.effectiveFilterDepth,y=u.effectiveFilterHeight,w=u.effectiveFilterWidth,C=b-1-u.padInfo.front,T=w-1-u.padInfo.left,E=y-1-u.padInfo.top,R=Tt(i.shape,"float32"),_=t.bufferSync(r);for(let k=0;k=u.outDepth||Math.floor(J)!==J))for(let ae=0;ae=u.outHeight||Math.floor(he)!==he))for(let j=0;j=u.outWidth||Math.floor(ne)!==ne)continue;const ge=b*y*w-1-d.get(k,J,he,ne,F),be=K*y*w+ae*w+j,Te=ge===be?1:0;if(Te===0)continue;const ve=_.get(k,J,he,ne,F);X+=ve*Te}}}R.set(X,k,B,M,P,F)}return t.makeTensorInfo(R.shape,R.dtype,R.values)}const dB={kernelName:q0,backendName:"cpu",kernelFunc:hB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pB(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:i,output:o}=e,a=i;nt([i,o],"maxPoolGrad");const{filterSize:l,strides:c,pad:u,dimRoundingMode:h}=s,d=Rs(a.shape,l,c,1,u,h),p=t.data.get(a.dataId).values,f=Tt(d.outShape,a.dtype,cE(p,a.shape,a.dtype,d).values),x=d.strideHeight,m=d.strideWidth,g=d.dilationHeight,v=d.dilationWidth,b=d.effectiveFilterHeight,y=d.effectiveFilterWidth,w=y-1-d.padInfo.left,C=b-1-d.padInfo.top,T=Tt(a.shape,"float32"),E=t.data.get(r.dataId).values,R=Tt(r.shape,"float32",E);for(let _=0;_=d.outHeight||Math.floor(U)!==U))for(let X=0;X=d.outWidth||Math.floor(K)!==K)continue;const J=b*y-1-f.get(_,U,K,k),ae=q*y+X,he=J===ae?1:0;if(he===0)continue;const j=R.get(_,U,K,k);L+=j*he}}T.set(L,_,F,B,k)}return t.makeTensorInfo(T.shape,T.dtype,T.values)}const fB={kernelName:H0,backendName:"cpu",kernelFunc:pB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mB(n,e,t,s,r){const i=it(e),o=Hv(n,e,t,i,r,"max"),a=cE(n,e,t,r,!0,s);return[o.values,a.values]}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gB={kernelName:f2,backendName:"cpu",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{x:s}=n,{filterSize:r,strides:i,pad:o,includeBatchInIndex:a}=e,l=t;nt(s,"MaxPoolWithArgmax");const c=l.data.get(s.dataId).values,u=Rs(s.shape,r,i,[1,1],o),[h,d]=mB(c,s.shape,s.dtype,a,u),p=l.write(h,u.outShape,s.dtype),f=l.write(d,u.outShape,s.dtype);return[{dataId:p,shape:u.outShape,dtype:s.dtype},{dataId:f,shape:u.outShape,dtype:"int32"}]}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xB(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i,keepDims:o}=s,a=It(i,r.shape),c=Wn(r.shape,a)[1],u=re(c),h=[],d=t.makeTensorInfo([],"float32",new Float32Array([u]));h.push(d);const p=da({inputs:{x:r},backend:t,attrs:{dtype:"float32"}});h.push(p);const f=qv({inputs:{a:p,b:d},backend:t});h.push(f);const x=mp({inputs:{x:f},backend:t,attrs:{axis:i,keepDims:o}});return h.forEach(m=>t.disposeIntermediateTensorInfo(m)),x}const vB={kernelName:Md,backendName:"cpu",kernelFunc:xB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bB(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i,keepDims:o}=s;nt(r,"min");const a=It(i,r.shape);let l=a;const c=ln(l,r.shape.length);let u=r;c!=null&&(u=ir({inputs:{x:r},backend:t,attrs:{perm:c}}),l=xn(l.length,r.shape.length)),Kn("min",l,u.shape.length);const[h,d]=Wn(u.shape,l),p=re(d),f=Cs(re(h),u.dtype),x=t.data.get(u.dataId).values;for(let g=0;gb[0]+r.shape[y]+b[1]),l=i.map(b=>b[0]),c=i.map((b,y)=>b[0]+r.shape[y]),u=o==="reflect"?0:1,h=t.data.get(r.dataId).values,d=r.shape.length,p=it(r.shape),f=re(a),x=a.length,m=it(a),g=hs(r.dtype,f);for(let b=0;b=c[C]&&(y[C]=(c[C]-1)*2-y[C]+u);y=y.map((C,T)=>C-l[T]);const w=Gi(y,d,p);g[b]=h[w]}return{dataId:t.write(g,a,r.dtype),shape:a,dtype:r.dtype}}const SB={kernelName:$d,backendName:"cpu",kernelFunc:wB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const CB=Hn((n,e)=>{const t=n%e;return n<0&&e<0||n>=0&&e>=0?t:(t+e)%e}),_B=is(_u,CB),TB={kernelName:_u,backendName:"cpu",kernelFunc:_B};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mE(n){const{inputs:e,backend:t,attrs:s}=n,{logits:r}=e,{dim:i}=s,o=r.shape.length;let a=i;if(a===-1&&(a=o-1),a!==o-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${o} and dim was ${a}`);const l=It([a],r.shape),c=fE({inputs:{x:r},backend:t,attrs:{reductionIndices:l,keepDims:!1}}),u=Vn(c.shape,l),h=gn({inputs:{x:c},backend:t,attrs:{shape:u}}),d=Gv({inputs:{a:r,b:h},backend:t}),p=vI({inputs:{x:d},backend:t}),f=mp({inputs:{x:p},backend:t,attrs:{axis:l,keepDims:!1}}),x=gn({inputs:{x:f},backend:t,attrs:{shape:u}}),m=qv({inputs:{a:p,b:x},backend:t});return t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(x),m}const IB={kernelName:Zd,backendName:"cpu",kernelFunc:mE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function EB(n){const{inputs:e,backend:t,attrs:s}=n,{logits:r}=e,{numSamples:i,seed:o,normalized:a}=s;nt(r,"multinomial");const l=a?r:mE({inputs:{logits:r},backend:t,attrs:{dim:-1}}),c=l.shape[0],u=l.shape[1],h=t.data.get(l.dataId).values,d=[c,i],p=Cs(re(d),"int32");for(let f=0;f=0&&h[d]{y0(i,u.shape,"All tensors passed to stack must have matching shapes"),N(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=[],l=e.map(u=>{const h=Jf({inputs:{input:u},backend:t,attrs:{dim:r}});return a.push(h),h}),c=Fc({inputs:l,backend:t,attrs:{axis:r}});return a.forEach(u=>t.disposeIntermediateTensorInfo(u)),c}const VB={kernelName:Od,backendName:"cpu",kernelFunc:xE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function WB(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{paddings:i,constantValue:o}=s;nt(r,"pad");const a=i.map((v,b)=>v[0]+r.shape[b]+v[1]),l=i.map(v=>v[0]),c=t.data.get(r.dataId).values,u=re(r.shape),h=r.shape.length,d=it(r.shape),p=re(a),f=a.length,x=it(a),m=hs(r.dtype,p);o!==0&&m.fill(o);for(let v=0;vC+l[T]),w=Gi(y,f,x);m[w]=c[v]}return{dataId:t.write(m,a,r.dtype),shape:a,dtype:r.dtype}}const vE={kernelName:zd,backendName:"cpu",kernelFunc:WB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const GB=Hn((n,e)=>Math.pow(n,e)),HB=is(Iu,GB),qB={kernelName:Iu,backendName:"cpu",kernelFunc:HB};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function XB(n){const{inputs:e,backend:t,attrs:s}=n,{paramsNestedSplits:r,paramsDenseValues:i,indices:o}=e,{outputRaggedRank:a}=s,l=r.map(g=>t.data.get(g.dataId).values),c=r.map(g=>g.shape),u=t.data.get(i.dataId).values,h=t.data.get(o.dataId).values,[d,p,f]=LI(l,c,u,i.shape,i.dtype,h,o.shape),x=d.map(g=>t.makeTensorInfo([g.length],"int32",g)),m=t.makeTensorInfo(f,i.dtype,p);return x.concat([m])}const KB={kernelName:QS,backendName:"cpu",kernelFunc:XB};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jB(n){const{inputs:e,backend:t}=n,{starts:s,limits:r,deltas:i}=e,o=t.data.get(s.dataId).values,a=t.data.get(r.dataId).values,l=t.data.get(i.dataId).values,[c,u]=FI(o,s.shape,s.dtype,a,r.shape,l,i.shape),h=t.makeTensorInfo([c.length],"int32",c),d=t.makeTensorInfo([u.length],s.dtype,u);return[h,d]}const YB={kernelName:eC,backendName:"cpu",kernelFunc:jB};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ZB(n){const{inputs:e,backend:t,attrs:s}=n,{shape:r,values:i,defaultValue:o,rowPartitionTensors:a}=e,{rowPartitionTypes:l}=s,c=t.data.get(r.dataId).values,u=t.data.get(i.dataId).values,h=t.data.get(o.dataId).values,d=a.map(m=>t.data.get(m.dataId).values),p=a.map(m=>m.shape),[f,x]=OI(c,r.shape,u,i.shape,i.dtype,h,o.shape,d,p,l);return t.makeTensorInfo(f,i.dtype,x)}const JB={kernelName:tC,backendName:"cpu",kernelFunc:ZB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function QB(n){const{backend:e,attrs:t}=n,{start:s,stop:r,dtype:i,step:o}=t,a=zI(s,r,o,i);return e.makeTensorInfo([a.length],i,a)}const eU={kernelName:j0,backendName:"cpu",kernelFunc:QB};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tU=sn(Eu,n=>1/n),nU={kernelName:Eu,backendName:"cpu",kernelFunc:tU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sU(n){const{inputs:e,backend:t,attrs:s}=n,{images:r}=e,{alignCorners:i,halfPixelCenters:o,size:a}=s;nt(r,"resizeBilinear");const l=it(r.shape),[c,u]=a,[h,d,p,f]=r.shape,x=t.data.get(r.dataId).values,m=new Float32Array(re([h,c,u,f])),g=[i&&c>1?d-1:d,i&&u>1?p-1:p],v=[i&&c>1?c-1:c,i&&u>1?u-1:u];let b=0;const y=g[0]/v[0],w=g[1]/v[1];for(let C=0;C1?c-1:c,o&&p>1?u-1:u],m=[o&&d>1?d-1:d,o&&p>1?p-1:p],g=x[0]/m[0],v=x[1]/m[1],b=t.data.get(i.dataId).values;let y=0;for(let w=0;w1?d-1:d,i&&u>1?p-1:p],v=[i&&c>1?c-1:c,i&&u>1?u-1:u],b=g[0]/v[0],y=g[1]/v[1];let w=0;for(let C=0;C1?u-1:u,o&&f>1?h-1:h],v=[o&&p>1?p-1:p,o&&f>1?f-1:f],b=g[0]/v[0],y=g[1]/v[1],w=1/b,C=1/y,T=Math.ceil(w)*2+2,E=Math.ceil(C)*2+2;for(let R=0;R=p)continue;const he=_+ae*l[1],j=ae*b,ne=Math.min(u-1,o?Math.round(j):Math.floor(j));if(k===ne)for(let ge=0;ge=f)continue;const Te=he+be*l[2],ve=be*y,Ge=Math.min(h-1,o?Math.round(ve):Math.floor(ve));P===Ge&&(K+=m[Te+X])}}x[L+X]=K}}}}return t.makeTensorInfo(r.shape,r.dtype,x)}const uU={kernelName:Z0,backendName:"cpu",kernelFunc:cU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function hU(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{dims:i}=s;nt(r,"reverse");const o=r.shape.length,a=It(i,r.shape);if(o===0)return eo({inputs:{x:r},backend:t});const l=new Ss(r.shape,r.dtype),c=t.bufferSync(r);for(let u=0;ud[p]=r.shape[p]-1-d[p]),l.set(c.get(...d),...h)}return t.makeTensorInfo(l.shape,l.dtype,l.values)}const dU={kernelName:Hd,backendName:"cpu",kernelFunc:hU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pU={kernelName:sm,backendName:"cpu",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{image:s}=n,{radians:r,fillValue:i,center:o}=e,a=t,l=hs(s.dtype,re(s.shape)),[c,u,h,d]=s.shape,[p,f]=wm(o,u,h),x=255,m=Math.sin(r),g=Math.cos(r),v=a.data.get(s.dataId).values;for(let y=0;y=0&&M=0&&P{const e=Math.floor(n);return n-e<.5?Math.floor(n):n-e>.5?Math.ceil(n):e%2===0?e:e+1}),mU={kernelName:Ru,backendName:"cpu",kernelFunc:fU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gU(n){const{inputs:e,backend:t,attrs:s}=n,{indices:r,updates:i}=e,{shape:o}=s,{sliceRank:a,numUpdates:l,sliceSize:c,strides:u,outputSize:h}=so(i,r,o),d=!0,p=t.bufferSync(r),f=t.bufferSync(i),x=nl(p,f,o,h,c,l,a,u,0,d);return t.makeTensorInfo(o,x.dtype,x.values)}const xU={kernelName:x2,backendName:"cpu",kernelFunc:gU};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vU(n,e){let t=0,s=n.length,r=0;for(;t1||r.shape.length===1?1:re(r.shape.slice(1));for(let f=0;fn>=0?IU*n:TU*(Math.exp(n)-1)),kU={kernelName:Nu,backendName:"cpu",kernelFunc:EU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const AU=sn(Pu,n=>n<0?-1:n>0?1:0),RU={kernelName:Pu,backendName:"cpu",kernelFunc:AU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const MU=sn($u,n=>Math.sin(n)),NU={kernelName:$u,backendName:"cpu",kernelFunc:MU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $U=sn(Du,n=>Math.sinh(n)),DU={kernelName:Du,backendName:"cpu",kernelFunc:$U};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const PU=11920928955078125e-23,jy=Math.log(PU)+2,LU=sn(Fu,n=>{const e=n>-jy,t=nNumber(m)))),t.makeTensorInfo([x.length],s.dtype,new Int32Array(x))]}const UU={kernelName:nC,backendName:"cpu",kernelFunc:BU};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function VU(n){const{inputs:e,backend:t}=n,{inputIndices:s,inputShape:r,newShape:i}=e;if(s.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape + ${s.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape + ${r.shape}`);if(i.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${i.shape}`);const o=Array.from(t.data.get(r.dataId).values),a=t.data.get(s.dataId).values,l=Array.from(t.data.get(i.dataId).values),[c,u,h]=GI(a,s.shape,s.dtype,o,l);return[t.makeTensorInfo(u,s.dtype,c),t.makeTensorInfo([h.length],i.dtype,new Int32Array(h))]}const WU={kernelName:sC,backendName:"cpu",kernelFunc:VU};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function GU(n){const{inputs:e,backend:t}=n,{data:s,indices:r,segmentIds:i}=e;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape + ${r.shape}`);if(i.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape + ${i.shape}`);if(r.shape[0]!==i.shape[0])throw new Error("segmentIds and indices should have same size.");const o=t.data.get(s.dataId).values,a=t.data.get(r.dataId).values,l=t.data.get(i.dataId).values,[c,u]=Wv(o,s.shape,s.dtype,a,l,!0);return t.makeTensorInfo(u,s.dtype,c)}const HU={kernelName:y2,backendName:"cpu",kernelFunc:GU};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qU(n){const{inputs:e,backend:t}=n,{data:s,indices:r,segmentIds:i}=e;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape + ${r.shape}`);if(i.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape + ${i.shape}`);if(r.shape[0]!==i.shape[0])throw new Error("segmentIds and indices should have same size.");const o=t.data.get(s.dataId).values,a=t.data.get(r.dataId).values,l=t.data.get(i.dataId).values,[c,u]=Wv(o,s.shape,s.dtype,a,l);return t.makeTensorInfo(u,s.dtype,c)}const XU={kernelName:w2,backendName:"cpu",kernelFunc:qU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function KU(n){const{inputs:e,backend:t,attrs:s}=n,{sparseIndices:r,sparseValues:i,defaultValue:o}=e,{outputShape:a}=s,{sliceRank:l,numUpdates:c,sliceSize:u,strides:h,outputSize:d}=so(i,r,a),p=!1,f=t.bufferSync(r);let x;switch(i.dtype){case"bool":{const m=t.bufferSync(i),g=!!t.data.get(o.dataId).values[0];x=nl(f,m,a,d,u,c,l,h,g,p);break}case"float32":{const m=t.bufferSync(i),g=t.data.get(o.dataId).values[0];x=nl(f,m,a,d,u,c,l,h,g,p);break}case"int32":{const m=t.bufferSync(i),g=t.data.get(o.dataId).values[0];x=nl(f,m,a,d,u,c,l,h,g,p);break}case"string":{const m=t.bufferSync(i),g=Ci(t.data.get(o.dataId).values[0]);x=nl(f,m,a,d,u,c,l,h,g,p);break}default:throw new Error(`Unsupported type ${i.dtype}`)}return t.makeTensorInfo(a,x.dtype,x.values)}const jU={kernelName:S2,backendName:"cpu",kernelFunc:KU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function YU(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{numOrSizeSplits:i,axis:o}=s,a=It(o,r.shape)[0],l=Pm(r,i,a),c=new Array(r.shape.length).fill(0),u=r.shape.slice();return l.map(h=>{const d=[...u];d[a]=h;const p=Cl({inputs:{x:r},backend:t,attrs:{begin:c,size:d}});return c[a]+=h,p})}const ZU={kernelName:Yd,backendName:"cpu",kernelFunc:YU};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const JU={kernelName:Q0,backendName:"cpu",kernelFunc:({inputs:n,backend:e})=>{const{x:t}=n,s=e;nt(t,"square");const r=s.data.get(t.dataId).values,i=new Float32Array(r.length);for(let a=0;a{const t=e;return isNaN(n)?NaN:n>0?1:t.alpha}),eV={kernelName:Gu,backendName:"cpu",kernelFunc:QU};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function tV(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{begin:i,end:o,strides:a,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:h,shrinkAxisMask:d}=s;nt(r,"stridedSlice");const{finalShapeSparse:p,finalShape:f,isIdentity:x,sliceDim0:m,isSimpleSlice:g,begin:v,end:b,strides:y}=pv(r.shape,i,o,a,l,c,u,h,d);let w;if(x)w=gn({inputs:{x:r},backend:t,attrs:{shape:f}});else if(m||g){N(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);const C=dv(v,b,y),T=Cl({inputs:{x:r},backend:t,attrs:{begin:v,size:C}});w=gn({inputs:{x:T},backend:t,attrs:{shape:f}}),t.disposeIntermediateTensorInfo(T)}else{const C=t.bufferSync(r),T=XI(p,C,y,v);w=t.makeTensorInfo(f,T.dtype,T.values)}return w}const nV={kernelName:em,backendName:"cpu",kernelFunc:tV};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sV(n){const{inputs:e,backend:t,attrs:s}=n,{separator:r,nGramWidths:i,leftPad:o,rightPad:a,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:h}=e,d=t.data.get(u.dataId).values,p=t.data.get(h.dataId).values,[f,x]=KI(d,p,r,i,o,a,l,c);return[t.makeTensorInfo([f.length],"string",f),t.makeTensorInfo(h.shape,"int32",x)]}const rV={kernelName:_2,backendName:"cpu",kernelFunc:sV};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function iV(n){const{inputs:e,backend:t,attrs:s}=n,{skipEmpty:r}=s,{input:i,delimiter:o}=e;if(i.dtype!=="string")throw new Error("Input must be of datatype string");if(i.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${i.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);const a=t.data.get(i.dataId).values,l=t.data.get(o.dataId).values[0],[c,u,h]=jI(a,l,r),d=u.length;return[t.makeTensorInfo([d,2],"int32",c),t.makeTensorInfo([d],"string",u),t.makeTensorInfo([2],"int32",new Int32Array(h))]}const oV={kernelName:rC,backendName:"cpu",kernelFunc:iV};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function aV(n){const{inputs:e,backend:t,attrs:s}=n,{numBuckets:r}=s,{input:i}=e;if(i.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");const o=t.data.get(i.dataId).values,a=YI(o,r);return t.makeTensorInfo(i.shape,"int32",a)}const lV={kernelName:iC,backendName:"cpu",kernelFunc:aV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cV=sn(Uu,n=>Math.tan(n)),uV={kernelName:Uu,backendName:"cpu",kernelFunc:cV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hV=sn(Vu,n=>Math.tanh(n)),dV={kernelName:Vu,backendName:"cpu",kernelFunc:hV};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pV(n){const{inputs:e,backend:t}=n,{tensor:s,indices:r,updates:i}=e,{sliceRank:o,numUpdates:a,sliceSize:l,strides:c,outputSize:u}=so(i,r,s.shape),h=!1,d=t.bufferSync(r),p=t.bufferSync(i),f=t.bufferSync(s),x=nl(d,p,s.shape,u,l,a,o,c,f,h);return t.makeTensorInfo(s.shape,x.dtype,x.values)}const fV={kernelName:v2,backendName:"cpu",kernelFunc:pV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mV(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{reps:i}=s;nt(r,"tile");const o=JI(t.bufferSync(r),i);return t.makeTensorInfo(o.shape,o.dtype,o.values)}const gV={kernelName:Wu,backendName:"cpu",kernelFunc:mV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xV(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{k:i,sorted:o}=s;nt(r,"topk");const a=t.data.get(r.dataId).values,[l,c]=eE(a,r.shape,r.dtype,i,o);return[t.makeTensorInfo(l.shape,l.dtype,l.values),t.makeTensorInfo(c.shape,c.dtype,c.values)]}const vV={kernelName:tm,backendName:"cpu",kernelFunc:xV};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bV(n){const{inputs:e,attrs:t,backend:s}=n,{image:r,transforms:i}=e,{interpolation:o,fillMode:a,fillValue:l,outputShape:c}=t,[u,h,d,p]=r.shape,[f,x]=c??[h,d],m=[u,f,x,p],g=it(r.shape),v=g[0],b=g[1],y=g[2],w=it(m),C=w[0],T=w[1],E=w[2],R=hs(r.dtype,re(m));R.fill(l);const _=s.data.get(r.dataId).values,k=s.data.get(i.dataId).values;for(let B=0;Be-1)if(e<=1)t=0;else{const s=2*e;t-=s*Math.trunc(t/s),t>=e&&(t=s-t-1)}return n2(0,t,e-1)}function SV(n,e){let t=n;if(t<0)if(e<=1)t=0;else{const s=e-1;t+=e*(Math.trunc(-t/s)+1)}else if(t>e-1)if(e<=1)t=0;else{const s=e-1;t-=e*Math.trunc(t/s)}return n2(0,t,e-1)}function CV(n,e){return n}function _V(n,e){return n2(0,n,e-1)}function Eh(n,e,t,s,r,i,o,a,l,c,u){const h=o*s+a*r+l*i+c;return 0<=a&&at.disposeIntermediateTensorInfo(f)),p}const NV={kernelName:Qd,backendName:"cpu",kernelFunc:MV};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $V=[EO,lF,AO,MO,fF,$O,PO,FO,zO,UO,WO,HO,XO,YO,JO,t9,s9,i9,a9,TO,c9,h9,p9,gF,m9,dF,vF,x9,cF,b9,w9,S9,_9,I9,k9,R9,N9,D9,L9,O9,B9,V9,G9,q9,X9,j9,Z9,Q9,ez,tz,nz,rz,az,vO,cz,bF,xz,yF,vz,SF,_z,Tz,Ez,_F,IF,Az,Mz,$z,Pz,kF,RF,uF,Fz,y9,zz,Uz,Wz,bO,NF,DF,Hz,LF,Xz,Yz,Jz,tB,sB,iB,oB,OF,lB,uB,dB,fB,gB,vB,yB,BF,SB,TB,kB,VF,GF,MB,DB,FB,qF,zB,UB,VB,vE,qB,wO,jF,KB,YB,JB,eU,hF,wx,nU,SO,CO,_O,rU,oU,lU,uU,dU,pU,mU,sO,xU,SU,_U,kU,iO,RU,NU,DU,oO,IB,FU,zU,UU,WU,HU,XU,jU,ZU,cO,JU,hO,pO,eV,nV,rV,oV,lV,xO,iz,uV,dV,fV,gV,vV,yV,XF,kV,RV,NV,BB];for(const n of $V)E2(n);/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ja={},Lp={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function DV(n,e){ja[n]=e}function ki(n,e){if(!(n in ja)||e!=null){const s=LV(n,e);if(s!==null)ja[n]=s;else return console.log("Could not get context for WebGL version",n),null}const t=ja[n];return t==null||t.isContextLost()?(delete ja[n],ki(n)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),ja[n])}function PV(n){if(!oe().getBool("IS_SAFARI")&&typeof OffscreenCanvas<"u"&&n===2)return new OffscreenCanvas(300,150);if(typeof document<"u")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function LV(n,e){if(n!==1&&n!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const t=e??PV(n);return t.addEventListener("webglcontextlost",s=>{s.preventDefault(),delete ja[n]},!1),oe().getBool("SOFTWARE_WEBGL_ENABLED")&&(Lp.failIfMajorPerformanceCaveat=!1),n===1?t.getContext("webgl",Lp)||t.getContext("experimental-webgl",Lp):t.getContext("webgl2",Lp)}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var qh;(function(n){n[n.DENSE=0]="DENSE",n[n.SHARED_BATCH=1]="SHARED_BATCH"})(qh||(qh={}));var Er;(function(n){n[n.RENDER=0]="RENDER",n[n.UPLOAD=1]="UPLOAD",n[n.PIXELS=2]="PIXELS",n[n.DOWNLOAD=3]="DOWNLOAD"})(Er||(Er={}));var ws;(function(n){n[n.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",n[n.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",n[n.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",n[n.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",n[n.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(ws||(ws={}));function gp(n,e){return[e,n]}function FV(n,e){return n*e}function Fp(n){const e=re(n),t=Math.ceil(e/4);return G1(t)}function Yu(n,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(n/2))]}function OV(n,e){const[t,s]=Yu(n,e);return t*s*4}function Kv(n,e){const t=n;let s,r,i,o,a,l,c,u,h,d;return oe().getNumber("WEBGL_VERSION")===2?(s=t.R32F,r=t.R16F,i=t.RGBA16F,o=t.RGBA32F,a=t.RED,c=4,u=1,h=t.HALF_FLOAT,d=t.FLOAT,l=t.RGBA8):(s=n.RGBA,r=n.RGBA,i=n.RGBA,o=t.RGBA,a=n.RGBA,c=4,u=4,h=e!=null?e.HALF_FLOAT_OES:null,d=n.FLOAT,l=n.RGBA),{internalFormatFloat:s,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:i,internalFormatPackedFloat:o,textureFormatFloat:a,downloadTextureFormat:l,downloadUnpackNumChannels:c,defaultNumChannels:u,textureTypeHalfFloat:h,textureTypeFloat:d}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function He(n,e){const t=e();return oe().getBool("DEBUG")&&zV(n),t}function zV(n){const e=n.getError();if(e!==n.NO_ERROR)throw new Error("WebGL Error: "+WV(n,e))}const BV=596e-10,UV=65504;function VV(n){return!!(oe().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||n===0||BVn.getExtension(e),'Extension "'+e+'" not supported on this browser.')}function GV(n,e){const t=$o(n,()=>n.createShader(n.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(He(n,()=>n.shaderSource(t,e)),He(n,()=>n.compileShader(t)),n.getShaderParameter(t,n.COMPILE_STATUS)===!1)throw console.log(n.getShaderInfoLog(t)),new Error("Failed to compile vertex shader.");return t}function HV(n,e){const t=$o(n,()=>n.createShader(n.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(He(n,()=>n.shaderSource(t,e)),He(n,()=>n.compileShader(t)),oe().get("ENGINE_COMPILE_ONLY"))return t;if(n.getShaderParameter(t,n.COMPILE_STATUS)===!1)throw bE(e,n.getShaderInfoLog(t)),new Error("Failed to compile fragment shader.");return t}const qV=/ERROR: [0-9]+:([0-9]+):/g;function bE(n,e){const t=qV.exec(e);if(t==null){console.log(`Couldn't parse line number in error: ${e}`),console.log(n);return}const s=+t[1],r=n.split(` +`),i=r.length.toString().length+2,o=r.map((h,d)=>yc((d+1).toString(),i)+h);let a=0;for(let h=0;hn.createProgram(),"Unable to create WebGLProgram.")}function KV(n,e){if(He(n,()=>n.linkProgram(e)),!oe().get("ENGINE_COMPILE_ONLY")&&n.getProgramParameter(e,n.LINK_STATUS)===!1)throw console.log(n.getProgramInfoLog(e)),new Error("Failed to link vertex and fragment shaders.")}function Og(n,e){if(He(n,()=>n.validateProgram(e)),n.getProgramParameter(e,n.VALIDATE_STATUS)===!1)throw console.log(n.getProgramInfoLog(e)),new Error("Shader program validation failed.")}function jV(n,e){const t=$o(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return He(n,()=>n.bindBuffer(n.ARRAY_BUFFER,t)),He(n,()=>n.bufferData(n.ARRAY_BUFFER,e,n.STATIC_DRAW)),t}function YV(n,e){const t=$o(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return He(n,()=>n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t)),He(n,()=>n.bufferData(n.ELEMENT_ARRAY_BUFFER,e,n.STATIC_DRAW)),t}function ZV(n){return $o(n,()=>n.createTexture(),"Unable to create WebGLTexture.")}function JV(n,e){const t=oe().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(n<=0||e<=0){const s=`[${n}x${e}]`;throw new Error("Requested texture size "+s+" is invalid.")}if(n>t||e>t){const s=`[${n}x${e}]`,r=`[${t}x${t}]`;throw new Error("Requested texture size "+s+" greater than WebGL maximum on this browser / GPU "+r+".")}}function QV(n){return $o(n,()=>n.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function Zy(n,e,t,s,r,i,o){const a=n.getAttribLocation(e,t);return a===-1?!1:(He(n,()=>n.bindBuffer(n.ARRAY_BUFFER,s)),He(n,()=>n.vertexAttribPointer(a,r,n.FLOAT,!1,i,o)),He(n,()=>n.enableVertexAttribArray(a)),!0)}function eW(n,e,t){iW(n,t),He(n,()=>n.activeTexture(n.TEXTURE0+t)),He(n,()=>n.bindTexture(n.TEXTURE_2D,e))}function tW(n,e,t){return $o(n,()=>n.getUniformLocation(e,t),'uniform "'+t+'" not present in program.')}function nW(n,e,t){return n.getUniformLocation(e,t)}function sW(n,e,t,s){He(n,()=>eW(n,e,s)),He(n,()=>n.uniform1i(t,s))}function zg(n,e,t){He(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,t)),He(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,e,0))}function Jy(n,e){He(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,e)),He(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,null,0))}function zp(n){const e=n.checkFramebufferStatus(n.FRAMEBUFFER);if(e!==n.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+rW(n,e))}function rW(n,e){switch(e){case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case n.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${e}`}}function $o(n,e,t){const s=He(n,()=>e());if(s==null)throw new Error(t);return s}function iW(n,e){const t=n.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,s=e+n.TEXTURE0;if(st){const r=`[gl.TEXTURE0, gl.TEXTURE${t}]`;throw new Error(`textureUnit must be in ${r}.`)}}function Oc(n,e=2){return re(n.slice(0,n.length-e))}function zc(n){if(n.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[n.length>1?n[n.length-2]:1,n[n.length-1]]}function Bp(n){let e=[1,1,1];return n.length===0||n.length===1&&n[0]===1||(e=[Oc(n),...zc(n)]),e}function oW(n,e=!1){let t=oe().getNumber("WEBGL_MAX_TEXTURE_SIZE"),s=oe().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");s===1/0&&oe().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(s=t/2),e&&(t=t*2,s=s*2,n=n.map((a,l)=>l>=n.length-2?s2(n[l]):n[l]),n.length===1&&(n=[2,n[0]])),n.length!==2&&(n=ba(n).newShape);let r=re(n),i=null;n.length<=1&&r<=t?i=[1,r]:n.length===2&&n[0]<=t&&n[1]<=t?i=n:n.length===3&&n[0]*n[1]<=t&&n[2]<=t?i=[n[0]*n[1],n[2]]:n.length===3&&n[0]<=t&&n[1]*n[2]<=t?i=[n[0],n[1]*n[2]]:n.length===4&&n[0]*n[1]*n[2]<=t&&n[3]<=t?i=[n[0]*n[1]*n[2],n[3]]:n.length===4&&n[0]<=t&&n[1]*n[2]*n[3]<=t&&(i=[n[0],n[1]*n[2]*n[3]]);const o=i!=null&&Math.max(...i)>s&&Math.min(...i)<=(e?2:1)&&Math.min(...i)>0;if(i==null||o)if(e){const a=Oc(n);let l=2,c=2;n.length&&([l,c]=zc(n)),r=a*(l/2)*(c/2),i=G1(r).map(u=>u*2)}else i=G1(r);return i}function Up(n){return n%2===0}function e0(n,e){if(n=n.slice(-2),e=e.slice(-2),Wt(n,e)||!n.length||!e.length||n[0]===0||n[1]===0||e[0]===0||e[1]===0)return!0;if(n.length!==e.length){const t=n[n.length-1],s=e[e.length-1];if(t===s||Up(t)&&Up(s)&&(n[0]===1||e[0]===1))return!0}return n[1]===e[1]&&Up(n[0])&&Up(e[0])}let Bg,Ug;function aW(n){if(Bg==null){const e=ki(n);Bg=e.getParameter(e.MAX_TEXTURE_SIZE)}return Bg}function lW(n){if(Ug==null){const e=ki(n);Ug=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Ug)}function cW(n){if(n===0)return 0;let e;const t=ki(n);return Zr(t,"EXT_disjoint_timer_query_webgl2")&&n===2?e=2:Zr(t,"EXT_disjoint_timer_query")?e=1:e=0,e}function Zr(n,e){return n.getExtension(e)!=null}function Qy(n){try{if(ki(n)!=null)return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function uW(n){if(n===0)return!1;const e=ki(n);if(n===1){if(!Zr(e,"OES_texture_float"))return!1}else if(!Zr(e,"EXT_color_buffer_float"))return!1;return Cx(e)}function hW(n){if(n===0)return!1;const e=ki(n);if(n===1){if(!Zr(e,"OES_texture_float")||!Zr(e,"WEBGL_color_buffer_float"))return!1}else{if(Zr(e,"EXT_color_buffer_float"))return Cx(e);const s="EXT_color_buffer_half_float";if(Zr(e,s)){const r=e.getExtension(s);return dW(e,r)}return!1}return Cx(e)}function Cx(n){const e=Kv(n),t=n.createTexture();n.bindTexture(n.TEXTURE_2D,t),n.texImage2D(n.TEXTURE_2D,0,e.internalFormatFloat,1,1,0,e.textureFormatFloat,e.textureTypeFloat,null);const i=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,i),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t,0);const o=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(t),n.deleteFramebuffer(i),o}function dW(n,e){const t=Kv(n,e),s=n.createTexture();n.bindTexture(n.TEXTURE_2D,s),n.texImage2D(n.TEXTURE_2D,0,t.internalFormatHalfFloat,1,1,0,t.textureFormatFloat,t.textureTypeHalfFloat,null);const o=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,o),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,s,0);const a=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(s),n.deleteFramebuffer(o),a}function pW(n){return n!==2?!1:ki(n).fenceSync!=null}function xp(n,e){Array.isArray(n)||(n=[n]),n.forEach(t=>{t!=null&&N(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the WebGL backend.`)})}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const st=oe();st.registerFlag("HAS_WEBGL",()=>st.getNumber("WEBGL_VERSION")>0);st.registerFlag("WEBGL_VERSION",()=>Qy(2)?2:Qy(1)?1:0);st.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);st.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>st.get("WEBGL_VERSION")===2);st.registerFlag("WEBGL_CPU_FORWARD",()=>!0);st.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);st.registerFlag("WEBGL_PACK",()=>st.getBool("HAS_WEBGL"));st.registerFlag("WEBGL_PACK_NORMALIZATION",()=>st.getBool("WEBGL_PACK"));st.registerFlag("WEBGL_PACK_CLIP",()=>st.getBool("WEBGL_PACK"));st.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>st.getBool("WEBGL_PACK"));st.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>st.getBool("WEBGL_PACK"));st.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>st.getBool("WEBGL_PACK"));st.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>st.getBool("WEBGL_PACK"));st.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>st.getBool("WEBGL_PACK"));st.registerFlag("WEBGL_PACK_REDUCE",()=>st.getBool("WEBGL_PACK"));st.registerFlag("WEBGL_LAZILY_UNPACK",()=>st.getBool("WEBGL_PACK"));st.registerFlag("WEBGL_CONV_IM2COL",()=>st.getBool("WEBGL_PACK"));st.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",()=>st.getBool("WEBGL_PACK"));st.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>aW(st.getNumber("WEBGL_VERSION")));st.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>lW(st.getNumber("WEBGL_VERSION")));st.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const n=st.getNumber("WEBGL_VERSION");return n===0?0:cW(n)});st.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>st.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!CC());st.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>uW(st.getNumber("WEBGL_VERSION")));st.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>st.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:st.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));st.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>hW(st.getNumber("WEBGL_VERSION")));st.registerFlag("WEBGL_FENCE_API_ENABLED",()=>pW(st.getNumber("WEBGL_VERSION")));st.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>st.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);st.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,n=>{if(typeof n!="number")throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${n}.`);if(n<0&&n!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${n}.`)});st.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>CC()?1:-1,n=>{if(typeof n!="number")throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${n}.`);if(n<0&&n!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${n}.`)});st.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);st.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);st.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);st.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);st.registerFlag("WEBGL_EXP_CONV",()=>!1);st.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>st.getBool("IS_TEST"));st.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0);st.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1);st.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1);st.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Vs(){let n,e,t,s,r,i,o,a,l,c;return oe().getNumber("WEBGL_VERSION")===2?(n="#version 300 es",e="in",t="out",s="in",r="texture",i="outputColor",o="out vec4 outputColor;",a=oe().getBool("WEBGL2_ISNAN_CUSTOM")?` + bool isnan_custom(float val) { + uint floatToUint = floatBitsToUint(val); + return (floatToUint & 0x7fffffffu) > 0x7f800000u; + } + + bvec4 isnan_custom(vec4 val) { + return bvec4(isnan_custom(val.x), + isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w)); + } + + #define isnan(value) isnan_custom(value) + `:"",l="",c=` + #define round(value) newRound(value) + int newRound(float value) { + return int(floor(value + 0.5)); + } + + ivec4 newRound(vec4 value) { + return ivec4(floor(value + vec4(0.5))); + } + `):(n="",e="attribute",t="varying",s="varying",r="texture2D",i="gl_FragColor",o="",a=` + #define isnan(value) isnan_custom(value) + bool isnan_custom(float val) { + return (val > 0. || val < 1. || val == 0.) ? false : true; + } + bvec4 isnan_custom(vec4 val) { + return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w)); + } + `,l=` + uniform float INFINITY; + + bool isinf(float val) { + return abs(val) == INFINITY; + } + bvec4 isinf(vec4 val) { + return equal(abs(val), vec4(INFINITY)); + } + `,c=` + int round(float value) { + return int(floor(value + 0.5)); + } + + ivec4 round(vec4 value) { + return ivec4(floor(value + vec4(0.5))); + } + `),{version:n,attribute:e,varyingVs:t,varyingFs:s,texture2D:r,output:i,defineOutput:o,defineSpecialNaN:a,defineSpecialInf:l,defineRound:c}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zl(n,e,t="index"){const s=it(e);return s.map((r,i)=>{const o=`int ${n[i]} = ${t} / ${r}`,a=i===s.length-1?`int ${n[i+1]} = ${t} - ${n[i]} * ${r}`:`index -= ${n[i]} * ${r}`;return`${o}; ${a};`}).join("")}function Km(n,e,t="index"){const s=it(e);return s.map((r,i)=>{const o=`int ${n[i]} = ${t} / outShapeStrides[${i}]`,a=i===s.length-1?`int ${n[i+1]} = ${t} - ${n[i]} * outShapeStrides[${i}]`:`index -= ${n[i]} * outShapeStrides[${i}]`;return`${o}; ${a};`}).join("")}function fW(n,e){const t=n.length,s=n.map(i=>`${e}[${i}]`),r=new Array(t-1);r[t-2]=s[t-1];for(let i=t-3;i>=0;--i)r[i]=`(${r[i+1]} * ${s[i+1]})`;return r}function mW(n,e,t="index"){const s=n.map((i,o)=>o),r=fW(s,e);return r.map((i,o)=>{const a=`int ${n[o]} = ${t} / ${r[o]}`,l=o===r.length-1?`int ${n[o+1]} = ${t} - ${n[o]} * ${r[o]}`:`index -= ${n[o]} * ${r[o]}`;return`${a}; ${l};`}).join("")}function jv(n){const e=it(n).map(t=>t.toString());return` + int getFlatIndex(ivec3 coords) { + return coords.x * ${e[0]} + coords.y * ${e[1]} + coords.z; + } +`}function Yv(){return` + int getFlatIndex(ivec3 coords) { + return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z; + } +`}const yE=` + const float FLOAT_MAX = 1.70141184e38; + const float FLOAT_MIN = 1.17549435e-38; + + lowp vec4 encode_float(highp float v) { + if (isnan(v)) { + return vec4(255, 255, 255, 255); + } + + highp float av = abs(v); + + if(av < FLOAT_MIN) { + return vec4(0.0, 0.0, 0.0, 0.0); + } else if(v > FLOAT_MAX) { + return vec4(0.0, 0.0, 128.0, 127.0) / 255.0; + } else if(v < -FLOAT_MAX) { + return vec4(0.0, 0.0, 128.0, 255.0) / 255.0; + } + + highp vec4 c = vec4(0,0,0,0); + + highp float e = floor(log2(av)); + highp float m = exp2(fract(log2(av))) - 1.0; + + c[2] = floor(128.0 * m); + m -= c[2] / 128.0; + c[1] = floor(32768.0 * m); + m -= c[1] / 32768.0; + c[0] = floor(8388608.0 * m); + + highp float ebias = e + 127.0; + c[3] = floor(ebias / 2.0); + ebias -= c[3] * 2.0; + c[2] += floor(ebias) * 128.0; + + c[3] += 128.0 * step(0.0, -v); + + return c / 255.0; + } +`;/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const{getBroadcastDims:wE}=o7;function gW(n,e,t){const s=[];if(n.forEach(p=>{const f=re(p.shapeInfo.logicalShape);if(p.shapeInfo.isUniform?s.push(`uniform float ${p.name}${f>1?`[${f}]`:""};`):(s.push(`uniform sampler2D ${p.name};`),s.push(`uniform int offset${p.name};`)),t.enableShapeUniforms){const{uniformShape:x}=Zv(t.packedInputs,p.shapeInfo.logicalShape,p.shapeInfo.texShape);switch(x.length){case 1:s.push(`uniform int ${p.name}Shape;`);break;case 2:s.push(`uniform ivec2 ${p.name}Shape;`);break;case 3:s.push(`uniform ivec3 ${p.name}Shape;`);break;case 4:s.push(`uniform ivec4 ${p.name}Shape;`);break}s.push(`uniform ivec2 ${p.name}TexShape;`)}}),t.enableShapeUniforms){switch(e.logicalShape.length){case 1:s.push("uniform int outShape;");break;case 2:s.push("uniform ivec2 outShape;"),s.push("uniform int outShapeStrides;");break;case 3:s.push("uniform ivec3 outShape;"),s.push("uniform ivec2 outShapeStrides;");break;case 4:s.push("uniform ivec4 outShape;"),s.push("uniform ivec3 outShapeStrides;");break}s.push("uniform ivec2 outTexShape;")}t.customUniforms&&t.customUniforms.forEach(p=>{s.push(`uniform ${p.type} ${p.name}${p.arrayIndex?`[${p.arrayIndex}]`:""};`)});const r=s.join(` +`),i=n.map(p=>xW(p,e,t.packedInputs,t.enableShapeUniforms)).join(` +`),o=e.texShape,a=Vs(),l=yW(a);let c,u,h=CW(a);return e.isPacked?(c=vW(e.logicalShape,o,t.enableShapeUniforms),u=SW(a)):(c=bW(e.logicalShape,o,t.enableShapeUniforms),u=wW(a)),t.packedInputs&&(h+=EW),[h,l,u,r,c,i,t.userCode].join(` +`)}function Zu(n,e=!1){const t=n.shapeInfo.logicalShape;switch(t.length){case 0:return zW(n,e);case 1:return UW(n,e);case 2:return WW(n,e);case 3:return HW(n,e);case 4:return XW(n,e);case 5:return KW(n);case 6:return jW(n);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function SE(n,e){switch(n.shapeInfo.logicalShape.length){case 0:return OW(n);case 1:return BW(n,e);case 2:return VW(n,e);case 3:return GW(n,e);default:return qW(n,e)}}function xW(n,e,t=!1,s){let r="";t?r+=SE(n,s):r+=Zu(n,s);const i=n.shapeInfo.logicalShape,o=e.logicalShape;return i.length<=o.length&&(t?r+=YW(n,e):r+=ZW(n,e)),r}function vW(n,e,t){switch(n.length){case 0:return CE();case 1:return kW(n,e,t);case 2:return LW(n,e,t);case 3:return RW(n,e,t);default:return NW(n,e,t)}}function bW(n,e,t){switch(n.length){case 0:return CE();case 1:return AW(n,e,t);case 2:return FW(n,e,t);case 3:return MW(n,e,t);case 4:return $W(n,e,t);case 5:return DW(n,e);case 6:return PW(n,e);default:throw new Error(`${n.length}-D output sampling is not yet supported`)}}function yW(n){return` + float sampleTexture(sampler2D textureSampler, vec2 uv) { + return ${n.texture2D}(textureSampler, uv).r; + } + `}function wW(n){return` + void setOutput(float val) { + ${n.output} = vec4(val, 0, 0, 0); + } + `}function SW(n){return` + void setOutput(vec4 val) { + ${n.output} = val; + } + `}function CW(n){return`${n.version} + precision highp float; + precision highp int; + precision highp sampler2D; + ${n.varyingFs} vec2 resultUV; + ${n.defineOutput} + const vec2 halfCR = vec2(0.5, 0.5); + + struct ivec5 + { + int x; + int y; + int z; + int w; + int u; + }; + + struct ivec6 + { + int x; + int y; + int z; + int w; + int u; + int v; + }; + + uniform float NAN; + ${n.defineSpecialNaN} + ${n.defineSpecialInf} + ${n.defineRound} + + int imod(int x, int y) { + return x - y * (x / y); + } + + int idiv(int a, int b, float sign) { + int res = a / b; + int mod = imod(a, b); + if (sign < 0. && mod != 0) { + res -= 1; + } + return res; + } + + //Based on the work of Dave Hoskins + //https://www.shadertoy.com/view/4djSRW + #define HASHSCALE1 443.8975 + float random(float seed){ + vec2 p = resultUV * seed; + vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1); + p3 += dot(p3, p3.yzx + 19.19); + return fract((p3.x + p3.y) * p3.z); + } + + ${_W} + ${TW} + ${IW} + `}const _W=` +vec2 uvFromFlat(int texNumR, int texNumC, int index) { + int texR = index / texNumC; + int texC = index - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +vec2 packedUVfrom1D(int texNumR, int texNumC, int index) { + int texelIndex = index / 2; + int texR = texelIndex / texNumC; + int texC = texelIndex - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +`,TW=` +vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR, + int texNumC, int row, int col) { + int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); + int texR = texelIndex / texNumC; + int texC = texelIndex - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +`,IW=` +vec2 packedUVfrom3D(int texNumR, int texNumC, + int texelsInBatch, int texelsInLogicalRow, int b, + int row, int col) { + int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2); + int texR = index / texNumC; + int texC = index - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +`,EW=` + float getChannel(vec4 frag, vec2 innerDims) { + vec2 modCoord = mod(innerDims, 2.); + return modCoord.x == 0. ? + (modCoord.y == 0. ? frag.r : frag.g) : + (modCoord.y == 0. ? frag.b : frag.a); + } + float getChannel(vec4 frag, int dim) { + float modCoord = mod(float(dim), 2.); + return modCoord == 0. ? frag.r : frag.g; + } +`;function CE(){return` + int getOutputCoords() { + return 0; + } + `}function kW(n,e,t){const s=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return s[0]===1?t?` + int getOutputCoords() { + return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0)); + } + `:` + int getOutputCoords() { + return 2 * int(resultUV.x * ${s[1]}.0); + } + `:s[1]===1?t?` + int getOutputCoords() { + return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0)); + } + `:` + int getOutputCoords() { + return 2 * int(resultUV.y * ${s[0]}.0); + } + `:t?` + int getOutputCoords() { + ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0)); + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(packedTexShape[0], packedTexShape[1])); + return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y); + } + `:` + int getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${s[0]}, ${s[1]})); + return 2 * (resTexRC.x * ${s[1]} + resTexRC.y); + } + `}function AW(n,e,t){return e[0]===1?t?` + int getOutputCoords() { + return int(resultUV.x * float(outTexShape[1])); + } + `:` + int getOutputCoords() { + return int(resultUV.x * ${e[1]}.0); + } + `:e[1]===1?t?` + int getOutputCoords() { + return int(resultUV.y * float(outTexShape[0])); + } + `:` + int getOutputCoords() { + return int(resultUV.y * ${e[0]}.0); + } + `:t?` + int getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(outTexShape[0], outTexShape[1])); + return resTexRC.x * outTexShape[1] + resTexRC.y; + } + `:` + int getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${e[0]}, ${e[1]})); + return resTexRC.x * ${e[1]} + resTexRC.y; + } + `}function RW(n,e,t){if(t)return` + ivec3 getOutputCoords() { + ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0)); + int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0)); + int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0)); + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(packedTexShape[0], packedTexShape[1])); + int index = resTexRC.x * packedTexShape[1] + resTexRC.y; + + int b = index / texelsInBatch; + index -= b * texelsInBatch; + + int r = 2 * (index / texelsInLogicalRow); + int c = imod(index, texelsInLogicalRow) * 2; + + return ivec3(b, r, c); + } + `;const s=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(n[2]/2),i=r*Math.ceil(n[1]/2);return` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${s[0]}, ${s[1]})); + int index = resTexRC.x * ${s[1]} + resTexRC.y; + + int b = index / ${i}; + index -= b * ${i}; + + int r = 2 * (index / ${r}); + int c = imod(index, ${r}) * 2; + + return ivec3(b, r, c); + } + `}function MW(n,e,t){if(t)return` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(outTexShape[0], outTexShape[1])); + int index = resTexRC.x * outTexShape[1] + resTexRC.y; + ${Km(["r","c","d"],n)} + return ivec3(r, c, d); + } +`;const s=zl(["r","c","d"],n);return` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${e[0]}, ${e[1]})); + int index = resTexRC.x * ${e[1]} + resTexRC.y; + ${s} + return ivec3(r, c, d); + } + `}function NW(n,e,t){if(t)return` + ivec4 getOutputCoords() { + ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0)); + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(packedTexShape[0], packedTexShape[1])); + int index = resTexRC.x * packedTexShape[1] + resTexRC.y; + + int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0)); + int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0)); + int texelsInBatchN = texelsInBatch * outShape[1]; + + int b2 = index / texelsInBatchN; + index -= b2 * texelsInBatchN; + + int b = index / texelsInBatch; + index -= b * texelsInBatch; + + int r = 2 * (index / texelsInLogicalRow); + int c = imod(index, texelsInLogicalRow) * 2; + + return ivec4(b2, b, r, c); + } + `;const s=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(n[n.length-1]/2),i=r*Math.ceil(n[n.length-2]/2);let o=i,a="",l="b, r, c";for(let c=2;c=1?u="coords = 0;":u=a.map(v=>`coords.${h[v+c]} = 0;`).join(` +`);let d="";o<2&&i>0?d="coords":d=n.shapeInfo.logicalShape.map((v,b)=>`coords.${h[b+c]}`).join(", ");let p="return outputValue;";const x=re(n.shapeInfo.logicalShape)===1,g=re(e.logicalShape)===1;if(i===1&&!x&&!g)p=` + return vec4(outputValue.xy, outputValue.xy); + `;else if(x&&!g)o===1?p=` + return vec4(outputValue.x, outputValue.x, 0., 0.); + `:p=` + return vec4(outputValue.x); + `;else if(a.length){const v=i-2,b=i-1;a.indexOf(v)>-1&&a.indexOf(b)>-1?p="return vec4(outputValue.x);":a.indexOf(v)>-1?p="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":a.indexOf(b)>-1&&(p="return vec4(outputValue.xx, outputValue.zz);")}return` + vec4 ${r}() { + ${l} coords = getOutputCoords(); + ${u} + vec4 outputValue = get${s}(${d}); + ${p} + } + `}function ZW(n,e){const t=n.name,s=t.charAt(0).toUpperCase()+t.slice(1),r="get"+s+"AtOutCoords",i=e.texShape,o=n.shapeInfo.texShape,a=n.shapeInfo.logicalShape.length,l=e.logicalShape.length;if(!n.shapeInfo.isUniform&&a===l&&n.shapeInfo.flatOffset==null&&Wt(o,i))return` + float ${r}() { + return sampleTexture(${t}, resultUV); + } + `;const c=an(l),u=wE(n.shapeInfo.logicalShape,e.logicalShape),h=l-a;let d;const p=["x","y","z","w","u","v"];a===0?d="":l<2&&u.length>=1?d="coords = 0;":d=u.map(x=>`coords.${p[x+h]} = 0;`).join(` +`);let f="";return l<2&&a>0?f="coords":f=n.shapeInfo.logicalShape.map((x,m)=>`coords.${p[m+h]}`).join(", "),` + float ${r}() { + ${c} coords = getOutputCoords(); + ${d} + return get${s}(${f}); + } + `}function an(n){if(n<=1)return"int";if(n===2)return"ivec2";if(n===3)return"ivec3";if(n===4)return"ivec4";if(n===5)return"ivec5";if(n===6)return"ivec6";throw Error(`GPU for rank ${n} is not yet supported`)}function Zv(n,e,t){const{newShape:s,keptDims:r}=ba(e),i=e.length,o=n&&i===3&&e[0]===1,a=o?e.slice(1):s,l=!n&&i>1&&!Wt(e,t)&&s.lengthn[t]).join(", ")}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function JW(n,e,t,s){const r=t.map((u,h)=>{const d={logicalShape:u.shape,texShape:u.isUniform?null:u.texData.texShape,isUniform:u.isUniform,isPacked:u.isUniform?!1:u.texData.isPacked,flatOffset:null};return u.texData!=null&&u.texData.slice!=null&&u.texData.slice.flatOffset>0&&(d.flatOffset=u.texData.slice.flatOffset),{name:e.variableNames[h],shapeInfo:d}}),i=r.map(u=>u.shapeInfo),o={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},a=gW(r,o,e),l=HV(n.gl,a),c=n.createProgram(l);return oe().get("ENGINE_COMPILE_ONLY")?{program:e,fragmentShader:l,source:a,webGLProgram:c,inShapeInfos:i,outShapeInfo:o,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(n.buildVao(c),Object.assign({program:e,fragmentShader:l,source:a,webGLProgram:c,inShapeInfos:i,outShapeInfo:o},_E(n,e,c)))}function _E(n,e,t){const s=[],r=[];let i,o,a,l=null,c=null;c=n.getUniformLocation(t,"NAN",!1),oe().getNumber("WEBGL_VERSION")===1&&(l=n.getUniformLocation(t,"INFINITY",!1));const u=!1;for(const h of e.variableNames){const d={name:h,uniform:n.getUniformLocation(t,h,u),offset:n.getUniformLocation(t,`offset${h}`,u)};e.enableShapeUniforms&&(d.shape=n.getUniformLocation(t,`${h}Shape`,u),d.texShape=n.getUniformLocation(t,`${h}TexShape`,u)),s.push(d)}if(e.enableShapeUniforms&&(i=n.getUniformLocation(t,"outShape",u),a=n.getUniformLocation(t,"outShapeStrides",u),o=n.getUniformLocation(t,"outTexShape",u)),e.customUniforms)for(const h of e.customUniforms)r.push(n.getUniformLocation(t,h.name,u));return{variablesLocations:s,customUniformLocations:r,infLoc:l,nanLoc:c,outShapeLocation:i,outShapeStridesLocation:a,outTexShapeLocation:o}}function ew(n,e){if(n.length!==e.length)throw Error(`Binary was compiled with ${n.length} inputs, but was executed with ${e.length} inputs`);n.forEach((t,s)=>{const r=t.logicalShape,i=e[s],o=i.shape;if(!Wt(r,o))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${o} must match`);if(t.isUniform&&i.isUniform)return;const a=t.texShape,l=i.isUniform?null:i.texData.texShape;if(!Wt(a,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${a} and ${l} must match`)})}function QW(n,e,t,s,r){e.program.enableShapeUniforms||(ew(e.inShapeInfos,t),ew([e.outShapeInfo],[s]));const i=s.texData.texture,o=s.texData.texShape;s.texData.isPacked?n.setOutputPackedMatrixTexture(i.texture,o[0],o[1]):n.setOutputMatrixTexture(i.texture,o[0],o[1]),n.setProgram(e.webGLProgram),n.bindVertexArray(e.webGLProgram.vao),oe().getNumber("WEBGL_VERSION")===1&&e.infLoc!==null&&n.gl.uniform1f(e.infLoc,1/0),e.nanLoc!==null&&n.gl.uniform1f(e.nanLoc,NaN);for(let l=0;l{const a=o.texData!=null&&o.texData.slice!=null&&o.texData.slice.flatOffset>0;if(n.enableShapeUniforms&&!o.isUniform){const l=o.texData.texShape,{useSqueezeShape:c,uniformShape:u,keptDims:h}=Zv(n.packedInputs,o.shape,l);let d="",p="",f="";if(u.length===1&&n.packedInputs){const w=[Math.ceil(l[0]/2),Math.ceil(l[1]/2)];d=`${w[0]>1}_${w[1]>1}`}else if(u.length===2&&!n.packedInputs)p=`${u[0]>1}_${u[1]>1}`;else if(u.length>2&&!n.packedInputs){const w=it(u);f=`${w[0]===l[1]}_${w[w.length-1]===l[1]}`}const x=o.shape.length,m=u.length===2&&Wt(o.shape,l),g=re(o.shape)===1,v=oa(o.shape,t.shape),b=!n.packedInputs&&x===t.shape.length&&Wt(l,t.texData.texShape),y=n.packedInputs||u.length>2?"":`${l[0]>1}_${l[1]>1}`;s+=`${x}_${b}_${c?h:""}_${u.length}_${g}_${v}_${m}_${d}_${p}_${f}_${y}_${a}`}else{const l=o.isUniform?"uniform":o.texData.texShape;s+=`${o.shape}_${l}_${a}`}});const r=n.userCode;let i=n.constructor.name;return i+="_"+s+"_"+r+`${oe().getNumber("WEBGL_VERSION")}`,i}function Ns(n){return oe().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&n<=4}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class tG{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=qh.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=Vs();this.outputShape=e,this.enableShapeUniforms=Ns(this.outputShape.length),this.userCode=` + ivec3 outCoordsFromFlatIndex(int index) { + ${this.enableShapeUniforms?Km(["r","c","d"],e):zl(["r","c","d"],e)} + return ivec3(r, c, d); + } + + void main() { + ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1])); + int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y); + + vec4 result = vec4(0.); + + for (int i=0; i<4; i++) { + int flatIndex = index + i; + ivec3 rc = outCoordsFromFlatIndex(flatIndex); + result[i] = getA(rc.x, rc.y, rc.z); + } + + ${t.output} = result; + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class nG{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=qh.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=Vs();this.outputShape=e,this.enableShapeUniforms=Ns(this.outputShape.length),this.userCode=` + ivec3 outCoordsFromFlatIndex(int index) { + ${this.enableShapeUniforms?Km(["r","c","d"],e):zl(["r","c","d"],e)} + return ivec3(r, c, d); + } + + void main() { + ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1])); + int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y); + + vec4 result = vec4(0.); + + for (int i=0; i<4; i++) { + int flatIndex = index + i; + ivec3 rc = outCoordsFromFlatIndex(flatIndex); + result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z)); + } + + ${t.output} = result; + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class sG{constructor(e){this.variableNames=["A"],this.outTexUsage=Er.DOWNLOAD;const t=Vs();this.outputShape=e,this.userCode=` + ${yE} + + void main() { + float x = getAAtOutCoords(); + ${t.output} = encode_float(x); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class rG{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Er.DOWNLOAD;const t=Vs();this.outputShape=e,this.userCode=` + ${yE} + + void main() { + ivec3 coords = getOutputCoords(); + float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z)); + ${t.output} = encode_float(x); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iG={R:0,G:1,B:2,A:3};class tw{constructor(e,t=!1,s="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const r=Vs();this.outputShape=e,this.enableShapeUniforms=Ns(this.outputShape.length);let i="result";t&&(i="floor(result * 255. + 0.5)");let o="";for(let a=0;an.bindTexture(a,o)),He(n,()=>n.texParameteri(a,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE)),He(n,()=>n.texParameteri(a,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)),He(n,()=>n.texParameteri(a,n.TEXTURE_MIN_FILTER,n.NEAREST)),He(n,()=>n.texParameteri(a,n.TEXTURE_MAG_FILTER,n.NEAREST)),oe().getNumber("WEBGL_VERSION")===1?He(n,()=>n.texImage2D(a,0,s,e,t,0,r,i,null)):He(n,()=>n.texStorage2D(a,1,s,e,t)),He(n,()=>n.bindTexture(n.TEXTURE_2D,null)),{texture:o,texShape:[t,e]}}function TE(n){return n.internalFormatFloat}function uG(n,e,t,s){const[r,i]=gp(e,t);return vp(n,r,i,TE(s),s.textureFormatFloat,n.FLOAT)}function IE(n){return n.internalFormatHalfFloat}function hG(n,e,t,s){const[r,i]=gp(e,t);return vp(n,r,i,IE(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function EE(n){return n.downloadTextureFormat}function dG(n,e,t,s){const[r,i]=gp(e,t);return vp(n,r,i,EE(s),n.RGBA,n.UNSIGNED_BYTE)}function kE(n){return n.internalFormatPackedFloat}function pG(n,e,t,s){const[r,i]=Yu(e,t);return vp(n,r,i,kE(s),n.RGBA,n.FLOAT)}function AE(n){return n.internalFormatPackedHalfFloat}function fG(n,e,t,s){const[r,i]=Yu(e,t);return vp(n,r,i,AE(s),n.RGBA,s.textureTypeHalfFloat)}function mG(n,e,t){return He(n,()=>n.bindBuffer(n.ARRAY_BUFFER,t)),Zy(n,e,"clipSpacePos",t,3,20,0)&&Zy(n,e,"uv",t,2,20,12)}function gG(n,e,t,s,r,i){He(n,()=>n.bindTexture(n.TEXTURE_2D,e));let o,a,l;r instanceof Uint8Array?(o=new Uint8Array(t*s*4),a=n.UNSIGNED_BYTE,l=n.RGBA):(o=new Float32Array(t*s*4),a=n.FLOAT,l=i.internalFormatPackedFloat),o.set(r),oe().getNumber("WEBGL_VERSION")===2?He(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,t,s,n.RGBA,a,o)):He(n,()=>n.texImage2D(n.TEXTURE_2D,0,l,t,s,0,n.RGBA,a,o)),He(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function xG(n,e,t){He(n,()=>n.bindTexture(n.TEXTURE_2D,e)),t.data instanceof Uint8Array?oe().getNumber("WEBGL_VERSION")===2?He(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,t.width,t.height,n.RGBA,n.UNSIGNED_BYTE,t.data)):He(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,t.width,t.height,0,n.RGBA,n.UNSIGNED_BYTE,t.data)):oe().getNumber("WEBGL_VERSION")===2?He(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,t)):He(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t)),He(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function vG(n,e,t,s){const r=n.createBuffer();He(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,r));const a=4*4*e*t;return He(n,()=>n.bufferData(n.PIXEL_PACK_BUFFER,a,n.STREAM_READ)),He(n,()=>n.readPixels(0,0,t,e,n.RGBA,n.FLOAT,0)),He(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,null)),r}function bG(n,e,t){const s=n,r=new Float32Array(t);return s.bindBuffer(s.PIXEL_PACK_BUFFER,e),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,r),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),r}function yG(n,e,t,s){const[r,i]=gp(e,t),o=4,a=new Uint8Array(FV(e*t,o));return He(n,()=>n.readPixels(0,0,r,i,s.downloadTextureFormat,n.UNSIGNED_BYTE,a)),new Float32Array(a.buffer)}function wG(n,e,t,s,r,i,o,a){const l=n,c=new Float32Array(OV(i,o));return l.bindBuffer(l.PIXEL_PACK_BUFFER,e),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,c),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),c}function SG(n,e,t){const s=new Float32Array(e*t*4);return He(n,()=>n.readPixels(0,0,t,e,n.RGBA,n.FLOAT,s)),s}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Vg{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const t=oe().getNumber("WEBGL_VERSION");if(e!=null?(this.gl=e,DV(t,e)):this.gl=ki(t),e=this.gl,oe().getNumber("WEBGL_VERSION")===2){const i=e;this.createVertexArray=()=>He(i,()=>i.createVertexArray()),this.bindVertexArray=o=>He(i,()=>i.bindVertexArray(o)),this.deleteVertexArray=o=>He(i,()=>i.deleteVertexArray(o)),this.getVertexArray=()=>He(i,()=>i.getParameter(i.VERTEX_ARRAY_BINDING))}else if(e!=null){const i=e.getExtension("OES_vertex_array_object");if(i==null)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>He(e,()=>i.createVertexArrayOES()),this.bindVertexArray=o=>He(e,()=>i.bindVertexArrayOES(o)),this.deleteVertexArray=o=>He(e,()=>i.deleteVertexArrayOES(o)),this.getVertexArray=()=>He(e,()=>e.getParameter(i.VERTEX_ARRAY_BINDING_OES))}let s="WEBGL_color_buffer_float";const r="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),oe().getNumber("WEBGL_VERSION")===1){const i="OES_texture_float",o="OES_texture_half_float";if(this.textureFloatExtension=Op(this.gl,i),Zr(this.gl,o))this.textureHalfFloatExtension=Op(this.gl,o);else if(oe().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(s),Zr(this.gl,r))this.colorBufferHalfFloatExtension=Op(this.gl,r);else if(oe().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(s="EXT_color_buffer_float",Zr(this.gl,s))this.colorBufferFloatExtension=this.gl.getExtension(s);else if(Zr(this.gl,r))this.colorBufferHalfFloatExtension=this.gl.getExtension(r);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=lG(this.gl),this.indexBuffer=cG(this.gl),this.framebuffer=QV(this.gl),this.textureConfig=Kv(this.gl,this.textureHalfFloatExtension)}get debug(){return oe().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;He(e,()=>e.finish()),He(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),He(e,()=>e.deleteFramebuffer(this.framebuffer)),He(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),He(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),He(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),uG(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),hG(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),dG(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),xG(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,s,r){this.throwIfDisposed(),gG(this.gl,e,t,s,r,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),fG(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),pG(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Jy(this.gl,this.framebuffer),this.outputTexture=null),He(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,s){return this.downloadMatrixDriver(e,()=>yG(this.gl,t,s,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,s,r,i,o){return wG(this.gl,e,t,s,r,i,o,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return bG(this.gl,e,t)}createBufferFromTexture(e,t,s){this.bindTextureToFrameBuffer(e);const r=vG(this.gl,t,s,this.textureConfig);return this.unbindTextureToFrameBuffer(),r}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,s;if(oe().getBool("WEBGL_FENCE_API_ENABLED")){const r=e,i=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),s=()=>{const o=r.clientWaitSync(i,0,0);return o===r.ALREADY_SIGNALED||o===r.CONDITION_SATISFIED},t=i}else oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),s=()=>this.isQueryAvailable(t,oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):s=()=>!0;return{query:t,isFencePassed:s}}downloadMatrixFromPackedTexture(e,t,s){return this.downloadMatrixDriver(e,()=>SG(this.gl,t,s))}createProgram(e){this.throwIfDisposed();const t=this.gl;this.vertexShader==null&&(this.vertexShader=aG(t));const s=XV(t);He(t,()=>t.attachShader(s,this.vertexShader)),He(t,()=>t.attachShader(s,e)),KV(t,s);const r=Object.assign(s,{vao:this.createVertexArray()});return this.debug&&Og(t,r),r}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);const t=this.gl;He(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer)),mG(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&(He(this.gl,()=>this.gl.deleteProgram(e)),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Og(this.gl,this.program),He(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,s=!0){return this.throwIfDisposed(),s?tW(this.gl,e,t):nW(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),He(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,s){this.throwIfDisposed(),this.throwIfNoProgram(),sW(this.gl,e,t,s)}setOutputMatrixTexture(e,t,s){this.setOutputMatrixTextureDriver(e,s,t)}setOutputPackedMatrixTexture(e,t,s){this.throwIfDisposed();const[r,i]=Yu(t,s);this.setOutputMatrixTextureDriver(e,r,i)}setOutputMatrixWriteRegion(e,t,s,r){this.setOutputMatrixWriteRegionDriver(s,e,r,t)}setOutputPackedMatrixWriteRegion(e,t,s,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&Og(this.gl,this.program),zp(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;if(this.debug){const t=this.getVertexArray();console.assert(t===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}He(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),He(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Op(this.gl,oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const s=this.gl,r=this.getQueryTimerExtensionWebGL2(),i=s.createQuery();return s.beginQuery(r.TIME_ELAPSED_EXT,i),i}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const t=this.gl,s=this.getQueryTimerExtensionWebGL2();t.endQuery(s.TIME_ELAPSED_EXT);return}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await Lb(()=>this.disposed||this.isQueryAvailable(e,oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){const s=this.gl;return s.getQueryParameter(e,s.QUERY_RESULT)/1e6}else{const s=this.getQueryTimerExtensionWebGL1();return s.getQueryObjectEXT(e,s.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){const s=this.gl,r=this.getQueryTimerExtensionWebGL2(),i=s.getQueryParameter(e,s.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint}else{const s=this.getQueryTimerExtensionWebGL1(),r=s.getQueryObjectEXT(e,s.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(s.GPU_DISJOINT_EXT)),r&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){const e=CG(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){const{resolveFn:s}=this.itemsToPoll[t];s()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let s;"setTimeoutCustom"in oe().platform&&(s=oe().platform.setTimeoutCustom.bind(oe().platform)),Lb(()=>(this.pollItems(),this.itemsToPoll.length===0),()=>0,null,s)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),zg(this.gl,e,this.framebuffer),this.debug&&zp(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(zg(this.gl,this.outputTexture,this.framebuffer),this.debug&&zp(this.gl)):Jy(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const s=t();return this.unbindTextureToFrameBuffer(),s}setOutputMatrixTextureDriver(e,t,s){this.throwIfDisposed();const r=this.gl;zg(r,e,this.framebuffer),this.debug&&zp(r),this.outputTexture=e,He(r,()=>r.viewport(0,0,t,s)),He(r,()=>r.scissor(0,0,t,s))}setOutputMatrixWriteRegionDriver(e,t,s,r){this.throwIfDisposed(),He(this.gl,()=>this.gl.scissor(e,t,s,r))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}}function CG(n){let e=0;for(;e`${n}.${t}`)}function Os(n,e){return e===1?[n]:$E(n,e)}function mH(n,e){if(n===1)return"rc";let t="";for(let s=0;s ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let s=this.rank-2;s= ${this.enableShapeUniforms?`outShape[${s}]`:this.outputShape[s]}`,s= ${s}; + bool rEdge = rp1 >= ${r}; + `}getOutput(e){const t=this.getSourceCoordsArr(e);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}), + cEdge ? 0. : getA(${t[1]}), + rEdge ? 0. : getA(${t[2]}), + rEdge || cEdge ? 0. : getA(${t[3]})`}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class DE{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=Ns(this.outputShape.length);let s="";for(let r=0;r<4;r++){let i="thisRC = rc;";r%2===1&&(i+="thisRC.z += 1;"),r>1&&(i+="thisRC.y += 1;"),s+=` + ${i} + ${r>0?"if(thisRC.y < rows && thisRC.z < cols){":""} + int flatIndex = getFlatIndex(thisRC); + + ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex); + vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z)); + + result[${r}] = + getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims); + ${r>0?"}":""} + `}this.userCode=` + ${xH(t,this.enableShapeUniforms)} + ${this.enableShapeUniforms?Yv():jv(e)} + + void main() { + ivec3 rc = getOutputCoords(); + + vec4 result = vec4(0.); + + ivec3 thisRC; + int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]}; + int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]}; + + ${s} + + setOutput(result); + } + `}}function xH(n,e){return` + ivec3 inputCoordsFromReshapedOutCoords(int index) { + ${e?mW(["r","c","d"],"inputShape"):zl(["r","c","d"],n)} + return ivec3(r, c, d); + } + `}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let vH=class{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(e,t,s){const r=sw(t,s),i=rw(e,r,s);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const o=nw(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,s);if(this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=o,this.log();const l=this.freeTextures[i].pop();return this.usedTextures[i].push(l),l}let a;return r===ws.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===ws.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===ws.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===ws.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===ws.PACKED_4X1_UNSIGNED_BYTE&&(a=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[i].push(a),this.numUsedTextures++,this._numBytesAllocated+=o,this.log(),a}releaseTexture(e,t,s,r){if(this.freeTextures==null)return;const i=sw(s,r),o=rw(t,i,r);o in this.freeTextures||(this.freeTextures[o]=[]);const a=nw(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,r),l=oe().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");l!==-1&&this._numBytesAllocated>l?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=a):(this.freeTextures[o].push(e),this.numFreeTextures++,this._numBytesFree+=a),this.numUsedTextures--;const c=this.usedTextures[o],u=c&&c.indexOf(e);if(u==null||u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");c[u]=c[c.length-1],c.pop(),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(const e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});for(const e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function bH(n,e){const t=n;if(e===t.R32F)return 4;if(e===t.R16F)return 2;if(e===t.RGBA32F)return 16;if(e===n.RGBA)return 16;if(e===t.RGBA16F)return 8;if(e===t.RGBA8)return 4;throw new Error(`Unknown internal format ${e}`)}function nw(n,e,t,s,r){const i=yH(e,s);let o;if(r){const[l,c]=Yu(n[0],n[1]);o=l*c}else{const[l,c]=gp(n[0],n[1]);o=l*c}const a=bH(t,i);return o*a}function yH(n,e){switch(n){case ws.PACKED_2X2_FLOAT32:return kE(e);case ws.PACKED_2X2_FLOAT16:return AE(e);case ws.UNPACKED_FLOAT32:return TE(e);case ws.UNPACKED_FLOAT16:return IE(e);case ws.PACKED_4X1_UNSIGNED_BYTE:return EE(e);default:throw new Error(`Unknown physical texture type ${n}`)}}function wH(n){return oe().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?n?ws.PACKED_2X2_FLOAT32:ws.UNPACKED_FLOAT32:n?ws.PACKED_2X2_FLOAT16:ws.UNPACKED_FLOAT16}function sw(n,e){if(n===Er.UPLOAD)return ws.PACKED_2X2_FLOAT32;if(n===Er.RENDER||n==null)return wH(e);if(n===Er.DOWNLOAD||n===Er.PIXELS)return ws.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${n}`)}function rw(n,e,t){return`${n[0]}_${n[1]}_${e}_${t}`}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Vi=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=Ns(this.outputShape.length),this.userCode=` + float unaryOperation(float x) { + ${t} + } + + void main() { + float x = getAAtOutCoords(); + float y = unaryOperation(x); + + setOutput(y); + } + `}};const ri="if (isnan(x)) return x;",SH="return x;",iw="return abs(x);",CH="return (x >= 0.0) ? x : (exp(x) - 1.0);",_H=ri+` + return (x < 0.0) ? 0.0 : x; +`,TH=ri+` + return (x < 0.0) ? 0.0 : min(6.0, x); +`,qo="return x;",IH="return 1.0 / (1.0 + exp(-1.0 * x));";/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const EH="return x;",kH=` + vec4 result; + + result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0); + result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0); + result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0); + result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0); + + return result; +`,AH=` + vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,RH=` + vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,MH="return 1.0 / (1.0 + exp(-1.0 * x));";class Yo{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=Ns(this.outputShape.length),this.userCode=` + vec4 unaryOperation(vec4 x) { + ${t} + } + + void main() { + vec4 x = getAAtOutCoords(); + vec4 y = unaryOperation(x); + + setOutput(y); + } + `}}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class NH{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=Ns(this.outputShape.length);const t=e.length,s=Os("rc",t),r=an(t),i=mH(t,s),o=s.slice(-2),a=t<=1?"rc":`vec2(${o.join(",")})`;this.userCode=` + void main() { + ${r} rc = getOutputCoords(); + vec4 packedInput = getA(${i}); + + setOutput(getChannel(packedInput, ${a})); + } + `}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $H=c4,DH=1e-7,PH=1e-4,Vp={};function LH(n){return n in Vp||(Vp[n]={}),Vp[n]}const FH=oe().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),OH=600;function zH(){return oe().global.screen==null?1024:oe().global.screen.height*oe().global.screen.width*window.devicePixelRatio*OH/1024/1024}class jm extends b0{nextDataId(){return jm.nextDataId++}constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!oe().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(e!=null){if(e instanceof Vg)t=e;else{const s=ki(oe().getNumber("WEBGL_VERSION"),e);t=new Vg(s)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const s=ki(oe().getNumber("WEBGL_VERSION"));t=new Vg(s),this.binaryCache=LH(oe().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new vH(this.gpgpu),this.numMBBeforeWarning=zH(),this.texData=new t2(this,Tr())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,s,r,i,o){const a=this.makeTensorInfo(t,s),l=this.texData.get(a.dataId);l.isPacked=!1,l.texture={texture:e,texShape:[r,i]},l.texShape=[r,i];const c=Bp(t),u=new tw(c,!1,o),h=this.runWebGLProgram(u,[a],s,[[r,i]]);return h.shape=t,l.texture=null,this.disposeIntermediateTensorInfo(a),h.dataId}write(e,t,s){if((oe().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||oe().getBool("DEBUG"))&&this.checkNumericalProblems(e),s==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const r={id:this.nextDataId()};return this.texData.set(r,{shape:t,dtype:s,values:e,usage:Er.UPLOAD,refCount:1}),r}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){const t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){const t=this.texData.get(e);t.refCount--}}move(e,t,s,r,i){if(oe().getBool("DEBUG")&&this.checkNumericalProblems(t),r==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:s,dtype:r,values:t,usage:Er.UPLOAD,refCount:i})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){const t=this.texData.get(e),{values:s,dtype:r,complexTensorInfos:i,slice:o,shape:a,isPacked:l}=t;if(o!=null){let d;l?d=new Yo(a,qo):d=new Vi(a,qo);const p=this.runWebGLProgram(d,[{dataId:e,shape:a,dtype:r}],r),f=this.readSync(p.dataId);return this.disposeIntermediateTensorInfo(p),f}if(s!=null)return this.convertAndCacheOnCPU(e);if(r==="string")return s;const c=this.activeTimers!=null;let u;c&&(u=qs());let h;if(r==="complex64"){const d=this.readSync(i.real.dataId),p=this.readSync(i.imag.dataId);h=_i(d,p)}else h=this.getValuesFromTexture(e);return c&&(this.downloadWaitMs+=qs()-u),this.convertAndCacheOnCPU(e,h)}async read(e){if(this.pendingRead.has(e)){const f=this.pendingRead.get(e);return new Promise(x=>f.push(x))}const t=this.texData.get(e),{values:s,shape:r,slice:i,dtype:o,complexTensorInfos:a,isPacked:l}=t;if(i!=null){let f;l?f=new Yo(r,qo):f=new Vi(r,qo);const x=this.runWebGLProgram(f,[{dataId:e,shape:r,dtype:o}],o),m=this.read(x.dataId);return this.disposeIntermediateTensorInfo(x),m}if(s!=null)return this.convertAndCacheOnCPU(e);if(oe().getBool("DEBUG")&&!oe().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&oe().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let c=null,u;if(o!=="complex64"&&oe().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);const f=this.texData.get(u.dataId);c=this.gpgpu.createBufferFromTexture(f.texture.texture,...Fp(r))}this.pendingRead.set(e,[]),o!=="complex64"&&await this.gpgpu.createAndWaitForFence();let h;if(o==="complex64"){const f=await Promise.all([this.read(a.real.dataId),this.read(a.imag.dataId)]),x=f[0],m=f[1];h=_i(x,m)}else if(c==null)h=this.getValuesFromTexture(e);else{const f=re(r);h=this.gpgpu.downloadFloat32MatrixFromBuffer(c,f)}if(u!=null&&this.disposeIntermediateTensorInfo(u),c!=null){const f=this.gpgpu.gl;He(f,()=>f.deleteBuffer(c))}const d=this.convertAndCacheOnCPU(e,h),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach(f=>f(d)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Tr().removeDataId(e,this),this.pendingDeletes--),d}readToGPU(e,t={}){const s=this.texData.get(e),{values:r,shape:i,slice:o,dtype:a,isPacked:l,texture:c}=s;if(a==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(o!=null){let p;l?p=new Yo(i,qo):p=new Vi(i,qo);const f=this.runWebGLProgram(p,[{dataId:e,shape:i,dtype:a}],a),x=this.readToGPU(f,t);return this.disposeIntermediateTensorInfo(f),x}if(c==null)throw r!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const u=this.decode(e,t.customTexShape),h=Tr().makeTensorFromTensorInfo(u),d=this.texData.get(u.dataId);return Object.assign({tensorRef:h},d.texture)}bufferSync(e){const t=this.readSync(e.dataId);if(e.dtype==="string")try{const s=t.map(r=>Ci(r));return Tt(e.shape,e.dtype,s)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return Tt(e.shape,e.dtype,t)}checkNumericalProblems(e){if(e!=null)for(let t=0;t0}time(e){const t=this.activeTimers,s=[];let r=!1;this.programTimersStack==null?(this.programTimersStack=s,r=!0):this.activeTimers.push(s),this.activeTimers=s,e();const i=ko(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),o=ko(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=t,r&&(this.programTimersStack=null);const a={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const l=await Promise.all(i);a.kernelMs=qS(l),a.getExtraProfileInfo=()=>l.map((c,u)=>({name:o[u],ms:c})).map(c=>`${c.name}: ${c.ms}`).join(", ")}else a.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,a})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:qs(),endMs:null}}endTimer(e){return oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=qs(),e)}async getQueryTime(e){if(oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);const{complexTensorInfos:s}=this.texData.get(e);return s!=null&&(this.disposeData(s.real.dataId,t),this.disposeData(s.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:t,dtype:s,texShape:r,usage:i,isPacked:o,slice:a}=this.texData.get(e),l=a&&a.origDataId||e,c=this.dataRefCount.get(l);c>1?this.dataRefCount.set(l,c-1):(this.dataRefCount.delete(l),t!=null&&(this.numBytesInGPU-=this.computeBytes(r,s),this.textureManager.releaseTexture(t,r,i,o)));const u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=FH){return oe().getBool("WEBGL_CPU_FORWARD")&&e.every(s=>this.texData.get(s.dataId).texture==null&&re(s.shape)0&&Kc(s[0])){const i=s.map(o=>_o(o));r=this.write(i,e,t)}else r=this.write(s,e,t);return this.texData.get(r).usage=null,{dataId:r,shape:e,dtype:t}}makeOutput(e,t,s){return Tr().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,s),this)}unpackTensor(e){const t=new NH(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new gH(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const s=[Oc(e.shape),...zc(e.shape)],r={dtype:e.dtype,shape:s,dataId:e.dataId},i=[Oc(t),...zc(t)],o=new DE(i,s),a=!0,l=[s],c=this.runWebGLProgram(o,[r],e.dtype,l,a);return{dataId:c.dataId,shape:t,dtype:c.dtype}}decode(e,t){const s=this.texData.get(e),{isPacked:r,shape:i,dtype:o}=s;if(t!=null){const d=re(i),p=t[0]*t[1]*4;N(d<=p,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}const a=Bp(i);let l;r?l=new nG(a):l=new tG(a);const c=!0,u=[t??Fp(a)],h=this.runWebGLProgram(l,[{shape:a,dtype:o,dataId:e}],o,u,c,t);return{dtype:o,shape:i,dataId:h.dataId}}runWebGLProgram(e,t,s,r,i=!1,o){const a=this.makeTensorInfo(e.outputShape,s),l=this.texData.get(a.dataId);if(e.packedOutput&&(l.isPacked=!0),e.outPackingScheme===qh.DENSE){const g=o??Fp(e.outputShape);l.texShape=g.map(v=>v*2)}if(e.outTexUsage!=null&&(l.usage=e.outTexUsage),re(a.shape)===0)return l.values=hs(a.dtype,0),a;const c=[],u=t.map(g=>{if(g.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let v=this.texData.get(g.dataId);if(v.texture==null){if(!e.packedInputs&&re(g.shape)<=oe().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:g.shape,texData:null,isUniform:!0,uniformValues:v.values};e.packedInputs&&(v.isPacked=!0,v.shape=g.shape)}if(this.uploadToGPU(g.dataId),!!v.isPacked!=!!e.packedInputs)g=v.isPacked?this.unpackTensor(g):this.packTensor(g),c.push(g),v=this.texData.get(g.dataId);else if(v.isPacked&&!e0(v.shape,g.shape)){const b=g,y=g.shape;g.shape=v.shape,g=this.packedReshape(g,y),c.push(g),v=this.texData.get(g.dataId),b.shape=y}return{shape:g.shape,texData:v,isUniform:!1}});this.uploadToGPU(a.dataId);const h={shape:a.shape,texData:l,isUniform:!1},d=eG(e,u,h),p=this.getAndSaveBinary(d,()=>JW(this.gpgpu,e,u,h)),f=this.activeTimers!=null;let x;f&&(x=this.startTimer()),oe().get("ENGINE_COMPILE_ONLY")||QW(this.gpgpu,p,u,h,r),c.forEach(g=>this.disposeIntermediateTensorInfo(g)),f&&(x=this.endTimer(x),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(x)}));const m=oe().getNumber("WEBGL_FLUSH_THRESHOLD");if(m>0){const g=qs();g-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=g)}if(!oe().getBool("WEBGL_LAZILY_UNPACK")&&l.isPacked&&i===!1){const g=this.unpackTensor(a);return this.disposeIntermediateTensorInfo(a),g}return a}compileAndRun(e,t,s,r,i=!1){return s=s||t[0].dtype,this.runWebGLProgram(e,t,s,r,i)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(oe().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(t=>{this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram),delete this.binaryCache[t]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement<"u"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=le(()=>{if(!oe().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=oe().getBool("DEBUG");oe().set("DEBUG",!1);const t=this.abs(Ht(1e-8)).dataSync()[0];if(oe().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?DH:PH}uploadToGPU(e){const t=this.texData.get(e),{shape:s,dtype:r,values:i,texture:o,usage:a,isPacked:l}=t;if(o!=null)return;const c=this.activeTimers!=null;let u;c&&(u=qs());let h=t.texShape;if(h==null&&(h=oW(s,l),t.texShape=h),i!=null){const d=Bp(s);let p,f=h[1],x=h[0];const m=i instanceof Uint8Array||i instanceof Uint8ClampedArray;(l||!m)&&([f,x]=Yu(h[0],h[1])),l?p=new oG(d,m):p=new tw(d,m);const g=m?[x,f]:h,v=this.makeTensorInfo(g,r),b=this.texData.get(v.dataId);m?b.usage=Er.PIXELS:b.usage=Er.UPLOAD,b.texShape=g,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(v.dataId),f,x,i);const y=[[x,f]],C=this.runWebGLProgram(p,[v],r,y,!0),T=this.texData.get(C.dataId);t.texShape=T.texShape,t.isPacked=T.isPacked,t.usage=T.usage,oe().get("ENGINE_COMPILE_ONLY")?this.disposeData(C.dataId):(t.texture=T.texture,t.values=null,this.texData.delete(C.dataId)),this.disposeIntermediateTensorInfo(v),c&&(this.uploadWaitMs+=qs()-u)}else{const d=this.acquireTexture(h,a,r,l);t.texture=d}}convertAndCacheOnCPU(e,t){const s=this.texData.get(e),{dtype:r}=s;return t!=null&&(s.values=BH(t,r)),s.values}acquireTexture(e,t,s,r){if(this.numBytesInGPU+=this.computeBytes(e,s),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){const i=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${i} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,r)}computeBytes(e,t){return e[0]*e[1]*Af(t)}checkCompileCompletion(){for(const[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){const e=[];if(this.gpgpu.parallelCompilationExtension){for(const[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}else{for(const[,t]of Object.entries(this.binaryCache)){const s=new Promise(r=>{try{this.checkCompletion_(t),r(!0)}catch(i){throw i}});e.push(s)}return Promise.all(e)}}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await w4(),this.checkCompletionAsync_(e))}checkCompletion_(e){if(this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)===!1)throw console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)===!1?(bE(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.")):new Error("Failed to link vertex and fragment shaders.");return!0}getUniformLocations(){for(const e of Object.values(this.binaryCache)){this.gpgpu.buildVao(e.webGLProgram);const{variablesLocations:t,customUniformLocations:s,infLoc:r,nanLoc:i,outShapeLocation:o,outShapeStridesLocation:a,outTexShapeLocation:l}=_E(this.gpgpu,e.program,e.webGLProgram);e.variablesLocations=t,e.customUniformLocations=s,e.infLoc=r,e.nanLoc=i,e.outShapeLocation=o,e.outShapeStridesLocation=a,e.outTexShapeLocation=l}}createTensorFromGPUData(e,t,s){e.channels=e.channels||"RGBA";const{texture:r,height:i,width:o,channels:a}=e,l=Tr().backend;if(!l.gpgpu.gl.isTexture(r))throw new Error("The texture is invalid. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through 'new tf.MathBackendWebGL(customCanvas)'.");const c=l.writeTexture(r,t,s,i,o,a);return Tr().makeTensorFromDataId(c,t,s,l)}}jm.nextDataId=0;function BH(n,e){if(e==="float32"||e==="complex64")return n;if(e==="int32"||e==="bool"){const t=e==="int32"?new Int32Array(n.length):new Uint8Array(n.length);for(let s=0;snew jm,2);/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qv=` + if (isnan(a)) return a; + if (isnan(b)) return b; +`;let _l=class{constructor(e,t,s){this.variableNames=["A","B"],this.outputShape=pt(t,s),this.enableShapeUniforms=Ns(this.outputShape.length),this.userCode=` + float binaryOperation(float a, float b) { + ${e} + } + + void main() { + float a = getAAtOutCoords(); + float b = getBAtOutCoords(); + setOutput(binaryOperation(a, b)); + } + `}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ul=` + result.r = isNaN.r ? NAN : result.r; + result.g = isNaN.g ? NAN : result.g; + result.b = isNaN.b ? NAN : result.b; + result.a = isNaN.a ? NAN : result.a; +`;class th{constructor(e,t,s,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=pt(t,s);const i=this.outputShape.length;this.enableShapeUniforms=Ns(i);let o="";if(r)if(i===0||re(this.outputShape)===1)o=` + result.y = 0.; + result.z = 0.; + result.w = 0.; + `;else if(o=` + ${an(i)} coords = getOutputCoords(); + `,i===1)this.enableShapeUniforms?o+=` + result.y = (coords + 1) >= outShape ? 0. : result.y; + result.z = 0.; + result.w = 0.; + `:o+=` + result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y; + result.z = 0.; + result.w = 0.; + `;else{const l=Os("coords",i);this.enableShapeUniforms?o+=` + bool nextRowOutOfBounds = + (${l[i-2]} + 1) >= outShape[${i} - 2]; + bool nextColOutOfBounds = + (${l[i-1]} + 1) >= outShape[${i} - 1]; + result.y = nextColOutOfBounds ? 0. : result.y; + result.z = nextRowOutOfBounds ? 0. : result.z; + result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w; + `:o+=` + bool nextRowOutOfBounds = + (${l[i-2]} + 1) >= ${this.outputShape[i-2]}; + bool nextColOutOfBounds = + (${l[i-1]} + 1) >= ${this.outputShape[i-1]}; + result.y = nextColOutOfBounds ? 0. : result.y; + result.z = nextRowOutOfBounds ? 0. : result.z; + result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w; + `}this.userCode=` + vec4 binaryOperation(vec4 a, vec4 b) { + ${e} + } + + void main() { + vec4 a = getAAtOutCoords(); + vec4 b = getBAtOutCoords(); + + vec4 result = binaryOperation(a, b); + ${o} + + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vr(n){const{inputs:e,backend:t}=n,{x:s}=e;return t.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const UH={kernelName:gu,backendName:"webgl",kernelFunc:vr};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ka(n){const{inputs:e,backend:t}=n,{real:s,imag:r}=e,i=t.makeTensorInfo(s.shape,"complex64"),o=t.texData.get(i.dataId),a=vr({inputs:{x:s},backend:t}),l=vr({inputs:{x:r},backend:t});return o.complexTensorInfos={real:a,imag:l},i}const VH={kernelName:E0,backendName:"webgl",kernelFunc:ka};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const PE="return (a < 0.) ? b * a : a;",LE=` + vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); + return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); +`;function WH(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{alpha:i}=s,o=t.makeTensorInfo([],"float32",ya(i,"float32")),a=oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new th(LE,r.shape,o.shape):new _l(PE,r.shape,o.shape),l=t.runWebGLProgram(a,[r,o],"float32");return t.disposeIntermediateTensorInfo(o),l}const GH={kernelName:wd,backendName:"webgl",kernelFunc:WH};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const FE="return (a < 0.) ? b * a : a;",OE=` + vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); + return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); +`;function HH(n){const{inputs:e,backend:t}=n,{x:s,alpha:r}=e,i=oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new th(OE,s.shape,r.shape):new _l(FE,s.shape,r.shape);return t.runWebGLProgram(i,[s,r],"float32")}const qH={kernelName:Bd,backendName:"webgl",kernelFunc:HH};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nh="if (isnan(x)) return x;";function Kt({opSnippet:n,packedOpSnippet:e,cpuKernelImpl:t,dtype:s}){return({inputs:r,backend:i})=>{const{x:o}=r,a=i,l=s||o.dtype;if(a.shouldExecuteOnCPU([o])&&t!=null){const h=a.texData.get(o.dataId),d=t(h.values,l);return a.makeTensorInfo(o.shape,l,d)}const c=oe().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&e!=null;let u;return c?u=new Yo(o.shape,e):u=new Vi(o.shape,n),a.runWebGLProgram(u,[o],l)}}function _s({opSnippet:n,packedOpSnippet:e,checkOutOfBounds:t=!1,supportsComplex:s=!1,cpuKernelImpl:r,dtype:i}){return({inputs:o,backend:a})=>{const{a:l,b:c}=o,u=a;if(s&&l.dtype==="complex64"){const f=u.texData.get(l.dataId),x=u.texData.get(c.dataId),[m,g]=[[f.complexTensorInfos.real,x.complexTensorInfos.real],[f.complexTensorInfos.imag,x.complexTensorInfos.imag]].map(b=>{const[y,w]=b,C={dataId:y.dataId,dtype:y.dtype,shape:l.shape},T={dataId:w.dataId,dtype:w.dtype,shape:c.shape},E=new _l(n,l.shape,c.shape);return u.runWebGLProgram(E,[C,T],ds(y.dtype,w.dtype))}),v=ka({inputs:{real:m,imag:g},backend:u});return u.disposeIntermediateTensorInfo(m),u.disposeIntermediateTensorInfo(g),v}const h=i||ds(l.dtype,c.dtype);if((l.dtype==="string"||c.dtype==="string"||u.shouldExecuteOnCPU([l,c]))&&r!=null){const f=u.texData.get(l.dataId).values,x=u.texData.get(c.dataId).values,m=l.dtype==="string"?Ti(f):f,g=l.dtype==="string"?Ti(x):x,[v,b]=r(l.shape,c.shape,m,g,h),y=u.makeTensorInfo(b,h),w=u.texData.get(y.dataId);return w.values=v,y}const d=oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&e!=null;let p;return d?p=new th(e,l.shape,c.shape,t):p=new _l(n,l.shape,c.shape),u.runWebGLProgram(p,[l,c],h)}}function Xh(n,e=!1){if(n==="linear")return e?EH:SH;if(n==="relu")return e?AH:_H;if(n==="elu")return e?kH:CH;if(n==="relu6")return e?RH:TH;if(n==="prelu")return e?OE:FE;if(n==="leakyrelu")return e?LE:PE;if(n==="sigmoid")return e?MH:IH;throw new Error(`Activation ${n} has not been implemented for the WebGL backend.`)}/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let zE=class{constructor(e,t,s,r=!1,i=!1,o=!1,a=null,l=!1,c=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=s,this.enableShapeUniforms=Ns(this.outputShape.length);const u=r?e[1]:e[2],h=Math.ceil(u/2),d=r?"i * 2, rc.y":"rc.y, i * 2",p=i?"rc.z, i * 2":"i * 2, rc.z",f=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],x=i?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let m="",g="";a&&(l?m=`vec4 activation(vec4 a) { + vec4 b = getPreluActivationWeightsAtOutCoords(); + ${a} + }`:c?m=`vec4 activation(vec4 a) { + vec4 b = getLeakyreluAlphaAtOutCoords(); + ${a} + }`:m=`vec4 activation(vec4 x) { + ${a} + }`,g="result = activation(result);");const v=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),l&&this.variableNames.push("preluActivationWeights"),c&&this.variableNames.push("leakyreluAlpha");let b="rc.x",y="rc.x";e[0]`The new shape (${l}) has ${c} elements and the old shape (${r.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`);const u=o.texData.get(r.dataId);return u.isPacked&&!e0(r.shape,l)&&!(u.texture!==null&&e0(u.shape,l))?KH(r,l,o):(o.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}const jH={kernelName:Vd,backendName:"webgl",kernelFunc:Be};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class cw{constructor(e,t){this.variableNames=["x"];const{windowSize:s,batchSize:r,inSize:i,outSize:o}=e;this.outputShape=[r,o];const a=Math.floor(s/4)*4,l=s%4;let c="sumValue += dot(values, ones);";if(t!=null){const h=1/t;c=`sumValue += dot(values * ${kc(h)?h.toPrecision(2):h}, ones);`}let u="";i%s>0&&(u=` + if (inIdx < 0 || inIdx >= ${i}) { + return 0.0; + } + `),this.userCode=` + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float getValue(int batch, int inIdx) { + ${u} + return getX(batch, inIdx); + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = outIdx * ${s}; + + float sumValue = 0.0; + + for (int i = 0; i < ${a}; i += 4) { + int inIdx = inOffset + i; + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + getValue(batch, inIdx + 3) + ); + + ${c} + } + + int inIdx = inOffset + ${a}; + if (${l===1}) { + vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0); + + ${c} + } else if (${l===2}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), 0.0, 0.0); + + ${c} + } else if (${l===3}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), 0.0); + + ${c} + } + setOutput(sumValue); + } + `}}/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let YH=class{constructor(e,t){this.variableNames=["x"];const{windowSize:s,batchSize:r,inSize:i,outSize:o}=e;this.outputShape=[r,o];let a="0.0",l="";t==="prod"?a="1.0":t==="min"?(a="1.0 / 1e-20",l="min"):t==="max"&&(a="-1.0 / 1e-20",l="max");let c=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?c="sumValue":t==="prod"?c="prodValue":t==="all"?c="allValue":t==="any"&&(c="anyValue");const u=Math.floor(s/4)*4,h=s%4;let d=` + if (${t==="sum"}) { + sumValue += dot(values, ones); + } else if (${t==="prod"}) { + vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]); + prodValue *= tmp[0] * tmp[1]; + } else { + minMaxValue = ${l}(values, minMaxValue); + if (${t==="min"} || ${t==="max"}) { + minMaxValue = ${l}(values, minMaxValue); + bvec4 isNaN = isnan(values); + if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) { + minMaxValue = vec4(NAN); + } + } + } + `,p="vec4";t==="all"?(a="1.0",d=` + bool reducedAllValue = all(values); + float floatedReducedAllValue = float(reducedAllValue); + allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0); + `,p="bvec4"):t==="any"&&(a="0.0",d=` + bool reducedAnyValue = any(values); + float floatedReducedAnyValue = float(reducedAnyValue); + anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0); + `,p="bvec4");let f="";i%s>0&&(f=` + if (inIdx < 0 || inIdx >= ${i}) { + return initializationValue; + } + `),this.userCode=` + const float initializationValue = ${a}; + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float getValue(int batch, int inIdx) { + ${f} + return getX(batch, inIdx); + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = outIdx * ${s}; + + vec4 minMaxValue = vec4(${a}); + float prodValue = 1.0; + float sumValue = 0.0; + float allValue = 1.0; + float anyValue = 0.0; + + for (int i = 0; i < ${u}; i += 4) { + int inIdx = inOffset + i; + ${p} values = ${p}( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + getValue(batch, inIdx + 3) + ); + + ${d} + } + + int inIdx = inOffset + ${u}; + if (${h===1}) { + ${p} values = ${p}( + getValue(batch, inIdx), + initializationValue, + initializationValue, + initializationValue + ); + + ${d} + } else if (${h===2}) { + ${p} values = ${p}( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + initializationValue, + initializationValue + ); + + ${d} + } else if (${h===3}) { + ${p} values = ${p}( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + initializationValue + ); + + ${d} + } + setOutput(${c}); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ZH(n){const e=[];for(;e.length===0||e[e.length-1].outSize!==1;){const t=e.length?e[e.length-1].outSize:n[1],s=ym(t);e.push({inSize:t,windowSize:s,outSize:Math.ceil(t/s)})}return e}function Vl(n,e,t,s){const r=ZH(n.shape);let i=n;for(let o=0;o6)throw Error(`Transpose for rank ${e} is not yet supported`);const t=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],s=new Array(e);for(let r=0;r6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const r=an(this.rank),i=$E("rc",this.rank),o=new Array(this.rank);for(let u=0;u`Error in matMul: inner shapes (${h}) and (${d}) of Tensors with shapes ${n.shape} and ${e.shape} and transposeA=${t} and transposeB=${s} must match.`);const w=t?[g,h,p]:[g,p,h],C=s?[v,f,d]:[v,d,f],T=Be({inputs:{x:n},backend:r,attrs:{shape:w}}),E=Be({inputs:{x:e},backend:r,attrs:{shape:C}}),R=[T,E],_=Math.max(g,v),k=t?T.shape[1]:T.shape[2],F=i!=null,B=o!=null,M=l==="leakyrelu",P=l!=null?Xh(l,!0):null,L=F||B||M||P!=null;let q;if((p===1||f===1)&&k>BE&&L===!1){let X=T,K=E;t&&(X=Us({inputs:{x:T},backend:r,attrs:{perm:[0,2,1]}}),R.push(X)),s&&(K=Us({inputs:{x:E},backend:r,attrs:{perm:[0,2,1]}}),R.push(K));const J=f!==1,ae=f===1;let he=X;J&&(he=Be({inputs:{x:X},backend:r,attrs:{shape:[_,k,1]}}),R.push(he));const j=f===1?2:1;let ne=K;ae&&(ne=Be({inputs:{x:K},backend:r,attrs:{shape:[_,1,k]}}),R.push(ne));const ge=eb({inputs:{a:he,b:ne},backend:r});q=Zm({inputs:{x:ge},backend:r,attrs:{axis:j,keepDims:!0}}),R.push(ge)}else{const X=ds(n.dtype,e.dtype),K=new zE(w,C,[_,p,f],t,s,F,P,B,M),J=[T,E];if(i!=null&&J.push(i),B&&J.push(o),M){const ae=r.makeTensorInfo([],"float32",ya(a,"float32"));J.push(ae),R.push(ae)}q=r.runWebGLProgram(K,J,X)}const U=Be({inputs:{x:q},backend:r,attrs:{shape:y}});R.push(q);for(const X of R)r.disposeIntermediateTensorInfo(X);return U}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rq(n){const{inputs:e,backend:t,attrs:s}=n,{a:r,b:i,bias:o,preluActivationWeights:a}=e,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:h}=s;return t0({a:r,b:i,transposeA:l,transposeB:c,backend:t,bias:o,preluActivationWeights:a,leakyreluAlpha:h,activation:u})}const iq={kernelName:Ph,backendName:"webgl",kernelFunc:rq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uw="return abs(x);";function oq(n){const{inputs:e,backend:t}=n,{x:s}=e;if(t.shouldExecuteOnCPU([s])&&s.dtype!=="complex64"){const i=t.texData.get(s.dataId),o=ME(i.values);return t.makeTensorInfo(s.shape,s.dtype,o)}let r;return oe().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Yo(s.shape,uw):r=new Vi(s.shape,uw),t.runWebGLProgram(r,[s],s.dtype)}const aq={kernelName:td,backendName:"webgl",kernelFunc:oq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const lq=ri+` + if (abs(x) > 1.) { + return NAN; + } + return acos(x); +`,cq=Kt({opSnippet:lq}),uq={kernelName:Yc,backendName:"webgl",kernelFunc:cq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hq=ri+` + if (x < 1.0) return NAN; +return log(x + sqrt(x * x - 1.0));`,dq=Kt({opSnippet:hq}),pq={kernelName:Zc,backendName:"webgl",kernelFunc:dq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hw="return a + b;",fq=_s({opSnippet:hw,packedOpSnippet:hw,supportsComplex:!0,cpuKernelImpl:_G}),mq={kernelName:El,backendName:"webgl",kernelFunc:fq};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class gq{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((i,o)=>`T${o}`);const s=[];this.variableNames.forEach(i=>{s.push(`float v${i} = get${i}AtOutCoords();`)});const r=this.variableNames.map(i=>`v${i}`).join(" + ");this.userCode=` + void main() { + ${s.join(` + `)} + + float result = ${r}; + setOutput(result); + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let xq=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((i,o)=>`T${o}`);const s=[];this.variableNames.forEach(i=>{s.push(`vec4 v${i} = get${i}AtOutCoords();`)});const r=this.variableNames.map(i=>`v${i}`).join(" + ");this.userCode=` + void main() { + ${s.join(` + `)} + + vec4 result = ${r}; + setOutput(result); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _f(n){const{inputs:e,backend:t}=n,s=e;if(s.length===1)return vr({inputs:{x:s[0]},backend:t});if(s.length>oe().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const l=Math.floor(s.length/2),c=_f({inputs:s.slice(0,l),backend:t}),u=_f({inputs:s.slice(l),backend:t});return _f({inputs:[c,u],backend:t})}const r=s.map(l=>l.dtype).reduce((l,c)=>ds(l,c)),i=s.map(l=>l.shape),a=oe().getBool("WEBGL_PACK")?new xq(s[0].shape,i):new gq(s[0].shape,i);return t.runWebGLProgram(a,s,r)}const vq={kernelName:w0,backendName:"webgl",kernelFunc:_f};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bq(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i,keepDims:o}=s,a=r.shape.length,l=It(i,r.shape);let c=l;const u=ln(c,a);let h=r;u!=null&&(h=Us({inputs:{x:r},backend:t,attrs:{perm:u}}),c=xn(c.length,a)),Kn("all",c,a);const[d,p]=Wn(h.shape,c),f=re(p),x=Be({inputs:{x:h},backend:t,attrs:{shape:[-1,f]}}),m=Vl(x,x.dtype,"all",t);let g;if(o){const v=Vn(d,l);g=Be({inputs:{x:m},backend:t,attrs:{shape:v}})}else g=Be({inputs:{x:m},backend:t,attrs:{shape:d}});return t.disposeIntermediateTensorInfo(x),t.disposeIntermediateTensorInfo(m),u!=null&&t.disposeIntermediateTensorInfo(h),g}const yq={kernelName:S0,backendName:"webgl",kernelFunc:bq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wq(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i,keepDims:o}=s,a=r.shape.length,l=It(i,r.shape);let c=l;const u=ln(c,a);let h=r;u!=null&&(h=Us({inputs:{x:r},backend:t,attrs:{perm:u}}),c=xn(c.length,a)),Kn("any",c,a);const[d,p]=Wn(h.shape,c),f=re(p),x=Be({inputs:{x:h},backend:t,attrs:{shape:[-1,f]}}),m=Vl(x,x.dtype,"any",t);let g;if(o){const v=Vn(d,l);g=Be({inputs:{x:m},backend:t,attrs:{shape:v}})}else g=Be({inputs:{x:m},backend:t,attrs:{shape:d}});return t.disposeIntermediateTensorInfo(x),t.disposeIntermediateTensorInfo(m),u!=null&&t.disposeIntermediateTensorInfo(h),g}const Sq={kernelName:C0,backendName:"webgl",kernelFunc:wq};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Cq=class{constructor(e,t,s){this.variableNames=["A"];const{windowSize:r,batchSize:i,outSize:o}=e;s||this.variableNames.push("bestIndicesA"),this.outputShape=[i,o];const a=t==="max"?">":"<",l=s?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = outIdx * ${r}; + + int bestIndex = inOffset; + float bestValue = getA(batch, bestIndex); + + for (int i = 0; i < ${r}; i++) { + int inIdx = ${l}; + float candidate = getA(batch, inIdx); + if (candidate ${a} bestValue) { + bestValue = candidate; + bestIndex = inIdx; + } + } + setOutput(float(bestIndex)); + } + `}};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class _q{constructor(e,t,s,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,N(e.length>2,()=>`Packed arg${s.charAt(0).toUpperCase()+s.slice(1)} supports only inputs with rank above 2.`);const i=e[e.length-1],o=Math.ceil(i/t);this.outputShape=e.slice(0,-1),o>1&&this.outputShape.push(o),r||this.variableNames.push("bestIndicesA");const a=this.outputShape,l=a.length,c=an(l),u=Os("coords",l);let h,d;if(o===1){d=l+1;const E=an(d);h=` + ${E} sourceLocR = ${E}(${u.join()}, 0); + ++${u[l-1]}; + ${E} sourceLocG = ${E}(${u.join()}, 0); + ++${u[l-2]}; + ${E} sourceLocA = ${E}(${u.join()}, 0); + --${u[l-1]}; + ${E} sourceLocB = ${E}(${u.join()}, 0); + --${u[l-2]};`}else d=l,h=` + ${c} sourceLocR = coords; + ++${u[l-1]}; + ${c} sourceLocG = coords; + ++${u[l-2]}; + ${c} sourceLocA = coords; + --${u[l-1]}; + ${c} sourceLocB = coords; + --${u[l-2]};`;const p=["x","y","z","w","u","v"].slice(0,d),f="."+p[d-1],x=p.map(E=>"int "+E),m=Os("sourceLocR",d-1).concat("inIdx.r"),g=Os("sourceLocG",d-1).concat("inIdx.g"),v=Os("sourceLocB",d-1).concat("inIdx.b"),b=Os("sourceLocA",d-1).concat("inIdx.a"),y=s==="max"?"greaterThan":"lessThan",w=r?"":` + inIdx = round(vec4(getBestIndicesAChannel(${m.join()}), + getBestIndicesAChannel(${g.join()}), + getBestIndicesAChannel(${v.join()}), + getBestIndicesAChannel(${b.join()})));`,C=`vec4( + getAChannel(${m.join()}), + hasNextCol ? getAChannel(${g.join()}) : 0., + hasNextRow ? getAChannel(${v.join()}) : 0., + hasNextRow && hasNextCol ? getAChannel(${b.join()}) : 0.)`,T=r?"":` + float getBestIndicesAChannel(${x.join()}) { + return getChannel(getBestIndicesA(${p.join()}), + vec2(${p.slice(-2).join()})); + }`;this.userCode=` + float getAChannel(${x.join()}) { + return getChannel(getA(${p.join()}), + vec2(${p.slice(-2).join()})); + } + ${T} + void main() { + ${c} coords = getOutputCoords(); + bool hasNextCol = ${u[l-1]} < ${a[l-1]-1}; + bool hasNextRow = ${u[l-2]} < ${a[l-2]-1}; + ${h} + ivec4 srcIdx = ivec4(sourceLocR${f}, sourceLocG${f}, + sourceLocB${f}, sourceLocA${f}) * ${t}; + ivec4 inIdx = srcIdx; + vec4 bestIndex = vec4(inIdx); + vec4 bestValue = ${C}; + + for (int i = 0; i < ${t}; i++) { + inIdx = srcIdx; + ${w} + vec4 candidate = ${C}; + bvec4 nan = isnan(candidate); + bvec4 replace = bvec4( + vec4(${y}(candidate, bestValue)) * (vec4(1.0) - vec4(nan))); + + bestValue = vec4(replace.x ? candidate.x : bestValue.x, + replace.y ? candidate.y : bestValue.y, + replace.z ? candidate.z : bestValue.z, + replace.w ? candidate.w : bestValue.w); + bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace)); + srcIdx++; + } + setOutput(bestIndex); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function UE(n,e,t,s=null){let r=e.shape[0],i=e.shape[1];s!=null&&(r=s.shape[0],i=s.shape[1]);const o=ym(i),a={windowSize:o,inSize:i,batchSize:r,outSize:Math.ceil(i/o)},l=new Cq(a,t,s==null),c=[e];s!=null&&c.push(s);const u=n.runWebGLProgram(l,c,"int32");if(u.shape[1]===1)return u;const h=UE(n,e,t,u);return n.disposeIntermediateTensorInfo(u),h}function VE(n,e,t,s=null){const r=s!=null?s.shape:e.shape,i=r[r.length-1],o=ym(i),a=new _q(r,o,t,s==null),l=s==null?[e]:[e,s],c=n.runWebGLProgram(a,l,"int32");if(c.shape.length===e.shape.length){const u=VE(n,e,t,c);return n.disposeIntermediateTensorInfo(c),u}return c}function WE(n,e,t,s){const r=[t];if(Kn("arg"+s.charAt(0).toUpperCase()+s.slice(1),r,e.shape.length),!oe().getBool("WEBGL_PACK_REDUCE")||e.shape.length<=2){const i=[],o=n.texData.get(e.dataId),a=o!==null&&o.isPacked;let l=e;a&&(l=n.unpackTensor(e),i.push(l));const[c,u]=Wn(l.shape,r),h=re(u),d=Be({inputs:{x:l},backend:n,attrs:{shape:[-1,h]}});i.push(d);const p=UE(n,d,s);i.push(p);const f=Be({inputs:{x:p},backend:n,attrs:{shape:c}});return i.forEach(x=>n.disposeIntermediateTensorInfo(x)),f}return VE(n,e,s)}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Tq(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i}=s;let o=It(i,r.shape);const a=ln(o,r.shape.length);let l=r;const c=[];a!=null&&(l=Us({inputs:{x:r},backend:t,attrs:{perm:a}}),c.push(l),o=xn(o.length,l.shape.length)),Kn("argMax",[o[0]],l.shape.length);const u=WE(t,l,o[0],"max");return c.forEach(h=>t.disposeIntermediateTensorInfo(h)),u}const Iq={kernelName:nd,backendName:"webgl",kernelFunc:Tq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Eq(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i}=s;let o=It(i,r.shape);const a=ln(o,r.shape.length);let l=r;const c=[];a!=null&&(l=Us({inputs:{x:r},backend:t,attrs:{perm:a}}),c.push(l),o=xn(o.length,l.shape.length)),Kn("argMin",[o[0]],l.shape.length);const u=WE(t,l,o[0],"min");return c.forEach(h=>t.disposeIntermediateTensorInfo(h)),u}const kq={kernelName:sd,backendName:"webgl",kernelFunc:Eq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Aq=ri+` + if (abs(x) > 1.) { + return NAN; + } + return asin(x); +`,Rq=Kt({opSnippet:Aq}),Mq={kernelName:Jc,backendName:"webgl",kernelFunc:Rq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Nq=ri+"return log(x + sqrt(x * x + 1.0));",$q=Kt({opSnippet:Nq}),Dq={kernelName:Qc,backendName:"webgl",kernelFunc:$q};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Pq=ri+` + return atan(x); +`,Lq=Kt({opSnippet:Pq}),Fq={kernelName:eu,backendName:"webgl",kernelFunc:Lq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Oq=Qv+` + return atan(a, b); +`,zq=` + vec4 result = atan(a, b); + bvec4 isNaNA = isnan(a); + bvec4 isNaNB = isnan(b); + bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w); + `+Ul+` + return result; +`,Bq=_s({opSnippet:Oq,packedOpSnippet:zq}),Uq={kernelName:nu,backendName:"webgl",kernelFunc:Bq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Vq=ri+` + if ((x < -1.0) || (x > 1.0)) return NAN; +return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,Wq=Kt({opSnippet:Vq}),Gq={kernelName:tu,backendName:"webgl",kernelFunc:Wq};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Kh=class{constructor(e,t,s,r=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&s)throw new Error("Cannot compute positions for average pool.");const o=e.filterWidth,a=e.strideHeight,l=e.strideWidth,c=e.dilationHeight,u=e.dilationWidth,h=e.effectiveFilterHeight,d=e.effectiveFilterWidth,p=e.padInfo.top,f=e.padInfo.left;this.outputShape=e.outShape;const x=t==="avg",m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let v="0.0";if(x||(v="-1.0 / 1e-20"),s){const E=">=";this.userCode=` + const ivec2 strides = ivec2(${a}, ${l}); + const ivec2 pads = ivec2(${p}, ${f}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d = coords[3]; + + ivec2 xRCCorner = coords.yz * strides - pads; + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // max/min x(?, ?, d) to get y(yR, yC, d). + // ? = to be determined + float minMaxValue = 0.0; + float minMaxValueFound = 0.0; + int minMaxPosition = 0; + float avgValue = 0.0; + + for (int wR = 0; wR < ${h}; + wR += ${c}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${d}; + wC += ${u}) { + int xC = xCCorner + wC; + + if (xC < 0 || xC >= ${e.inWidth}) { + continue; + } + + float value = getX(batch, xR, xC, d); + + // If a min / max value has already been found, use it. If not, + // use the current value. + float currMinMaxValue = mix( + value, minMaxValue, minMaxValueFound); + if (value ${E} currMinMaxValue) { + minMaxValue = value; + minMaxValueFound = 1.0; + minMaxPosition = ${r?i?m:g:`wR * ${d} + wC`}; + } + } + } + setOutput(float(minMaxPosition)); + } + `;return}const b="max";let y=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(y="avgValue / max(count, 1.0)");const w=Math.floor(o/4)*4,C=o%4,T=` + if (${x}) { + avgValue += dot(values, ones); + } else { + minMaxValue = ${b}(values, minMaxValue); + } + `;this.userCode=` + const ivec2 strides = ivec2(${a}, ${l}); + const ivec2 pads = ivec2(${p}, ${f}); + const float initializationValue = ${v}; + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float count = 0.0; + + float getValue(int batch, int xR, int xC, int d) { + if (xC < 0 || xC >= ${e.inWidth}) { + return initializationValue; + } + count += 1.0; + return getX(batch, xR, xC, d); + } + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d = coords[3]; + + ivec2 xRCCorner = coords.yz * strides - pads; + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // max/min x(?, ?, d) to get y(yR, yC, d). + // ? = to be determined + vec4 minMaxValue = vec4(${v}); + float avgValue = 0.0; + count = 0.0; + + for (int wR = 0; wR < ${h}; + wR += ${c}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${w}; wC += 4) { + int xC = xCCorner + wC * ${u}; + + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + ${u}, d), + getValue(batch, xR, xC + 2 * ${u}, d), + getValue(batch, xR, xC + 3 * ${u}, d) + ); + + ${T} + } + + int xC = xCCorner + ${w}; + if (${C===1}) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + initializationValue, + initializationValue, + initializationValue + ); + + ${T} + } else if (${C===2}) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + ${u}, d), + initializationValue, + initializationValue + ); + + ${T} + } else if (${C===3}) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + ${u}, d), + getValue(batch, xR, xC + 2 * ${u}, d), + initializationValue + ); + + ${T} + } + } + setOutput(${y}); + } + `}},tb=class{constructor(e,t,s,r=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&s)throw new Error("Cannot compute positions for average pool.");const o=e.filterWidth,a=e.strideDepth,l=e.strideHeight,c=e.strideWidth,u=e.dilationDepth,h=e.dilationHeight,d=e.dilationWidth,p=e.effectiveFilterDepth,f=e.effectiveFilterHeight,x=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,v=e.padInfo.left;this.outputShape=e.outShape;const b=t==="avg";let y="0.0";if(b||(y="-1.0 / 1e-20"),s){const _=">=";this.userCode=` + const ivec3 strides = + ivec3(${a}, ${l}, ${c}); + const ivec3 pads = ivec3(${m}, ${g}, ${v}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; + int xDCorner = xCorner.x; + int xRCorner = xCorner.y; + int xCCorner = xCorner.z; + + // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch). + // ? = to be determined + float minMaxValue = 0.0; + float minMaxValueFound = 0.0; + int minMaxPosition = 0; + + for (int wD = 0; wD < ${p}; + wD += ${u}) { + int xD = xDCorner + wD; + + if (xD < 0 || xD >= ${e.inDepth}) { + continue; + } + + for (int wR = 0; wR < ${f}; + wR += ${h}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${x}; + wC += ${d}) { + int xC = xCCorner + wC; + + if (xC < 0 || xC >= ${e.inWidth}) { + continue; + } + + float value = getX(batch, xD, xR, xC, ch); + + // If a min / max value has already been found, use it. If not, + // use the current value. + float currMinMaxValue = mix( + value, minMaxValue, minMaxValueFound); + if (value ${_} currMinMaxValue) { + minMaxValue = value; + minMaxValueFound = 1.0; + minMaxPosition = ${r?i?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${f} * ${x} + + wR * ${x} + wC`}; + } + } + } + } + setOutput(float(minMaxPosition)); + } + `;return}const w="max";let C=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(C="avgValue / max(count, 1.0)");const T=Math.floor(o/4)*4,E=o%4,R=` + if (${b}) { + avgValue += dot(values, ones); + } else { + minMaxValue = ${w}(values, minMaxValue); + } + `;this.userCode=` + const ivec3 strides = + ivec3(${a}, ${l}, ${c}); + const ivec3 pads = ivec3(${m}, ${g}, ${v}); + const float initializationValue = ${y}; + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float count = 0.0; + + float getValue(int batch, int xD, int xR, int xC, int ch) { + if (xC < 0 || xC >= ${e.inWidth}) { + return initializationValue; + } + count += 1.0; + return getX(batch, xD, xR, xC, ch); + } + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; + int xDCorner = xCorner.x; + int xRCorner = xCorner.y; + int xCCorner = xCorner.z; + + // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch). + // ? = to be determined + vec4 minMaxValue = vec4(${y}); + float avgValue = 0.0; + count = 0.0; + + for (int wD = 0; wD < ${p}; + wD += ${u}) { + int xD = xDCorner + wD; + + if (xD < 0 || xD >= ${e.inDepth}) { + continue; + } + + for (int wR = 0; wR < ${f}; + wR += ${h}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${T}; wC += 4) { + int xC = xCCorner + wC * ${d}; + + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + ${d}, ch), + getValue(batch, xD, xR, xC + 2 * ${d}, ch), + getValue(batch, xD, xR, xC + 3 * ${d}, ch) + ); + + ${R} + } + + int xC = xCCorner + ${T}; + if (${E===1}) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + initializationValue, + initializationValue, + initializationValue + ); + + ${R} + } else if (${E===2}) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + ${d}, ch), + initializationValue, + initializationValue + ); + + ${R} + } else if (${E===3}) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + ${d}, ch), + getValue(batch, xD, xR, xC + 2 * ${d}, ch), + initializationValue + ); + + ${R} + } + } + } + setOutput(${C}); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Hq(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e;xp(r,"avgPool");const{filterSize:i,strides:o,pad:a,dimRoundingMode:l}=s,c=1;N(gs(o,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const u=Rs(r.shape,i,o,c,a,l);if(u.filterWidth===1&&u.filterHeight===1&&Wt(u.inShape,u.outShape))return vr({inputs:{x:r},backend:t});const h=new Kh(u,"avg",!1);return t.runWebGLProgram(h,[r],"float32")}const qq={kernelName:rd,backendName:"webgl",kernelFunc:Hq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Xq(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{filterSize:i,strides:o,pad:a,dimRoundingMode:l,dataFormat:c}=s,u=[1,1,1],h=$r(r.shape,i,o,u,a,l,c),d=new tb(h,"avg",!1);return t.runWebGLProgram(d,[r],"float32")}const Kq={kernelName:id,backendName:"webgl",kernelFunc:Xq};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let jq=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,r=e.strideHeight,i=e.strideWidth,o=e.dilationHeight,a=e.dilationWidth,l=e.effectiveFilterHeight,c=e.effectiveFilterWidth,u=l-1-e.padInfo.top,h=c-1-e.padInfo.left,d=1/(t*s);this.userCode=` + const ivec2 pads = ivec2(${u}, ${h}); + const float avgMultiplier = float(${d}); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + + ivec2 dyRCCorner = coords.yz - pads; + int dyRCorner = dyRCCorner.x; + int dyCCorner = dyRCCorner.y; + + // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${l}; + wR += ${o}) { + float dyR = float(dyRCorner + wR) / ${r}.0; + + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${c}; + wC+= ${a}) { + float dyC = float(dyCCorner + wC) / ${i}.0; + + if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(b, idyR, idyC, d); + + dotProd += dyValue * avgMultiplier; + } + } + setOutput(dotProd); + } + `}},Yq=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,s=e.filterHeight,r=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,l=e.dilationDepth,c=e.dilationHeight,u=e.dilationWidth,h=e.effectiveFilterDepth,d=e.effectiveFilterHeight,p=e.effectiveFilterWidth,f=h-1-e.padInfo.front,x=d-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*s*r);this.userCode=` + const ivec3 pads = ivec3(${f}, ${x}, ${m}); + const float avgMultiplier = float(${g}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; + int dyDCorner = dyCorner.x; + int dyRCorner = dyCorner.y; + int dyCCorner = dyCorner.z; + + // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get + // dx(xD, xR, xC, ch). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + + for (int wD = 0; wD < ${h}; + wD += ${l}) { + float dyD = float(dyDCorner + wD) / ${i}.0; + + if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) { + continue; + } + int idyD = int(dyD); + + for (int wR = 0; wR < ${d}; + wR += ${c}) { + float dyR = float(dyRCorner + wR) / ${o}.0; + + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${p}; + wC += ${u}) { + float dyC = float(dyCCorner + wC) / ${a}.0; + + if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(batch, idyD, idyR, idyC, ch); + + dotProd += dyValue * avgMultiplier; + } + } + } + setOutput(dotProd); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Zq(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:i}=e,o=i,{filterSize:a,strides:l,pad:c,dimRoundingMode:u}=s,h=[1,1,1],d=$r(o.shape,a,l,h,c,u),p=new Yq(d);return t.runWebGLProgram(p,[r],o.dtype)}const Jq={kernelName:T0,backendName:"webgl",kernelFunc:Zq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Qq(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:i}=e,o=i;xp([r,i],"avgPoolGrad");const{filterSize:a,strides:l,pad:c}=s,u=Rs(o.shape,a,l,1,c),h=new jq(u);return t.runWebGLProgram(h,[r],o.dtype)}const eX={kernelName:_0,backendName:"webgl",kernelFunc:Qq};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function tX(n){const{inputs:e,backend:t,attrs:s}=n,{a:r,b:i}=e,{transposeA:o,transposeB:a}=s;return t0({a:r,b:i,transposeA:o,transposeB:a,backend:t})}const nX={kernelName:od,backendName:"webgl",kernelFunc:tX};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let sX=class{constructor(e,t,s,r,i,o){this.outputShape=[],this.variableNames=["x","mean","variance"],pt(e,t),pt(e,s);let a="0.0";r!=null&&(pt(e,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let l="1.0";i!=null&&(pt(e,i),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=` + void main() { + float x = getXAtOutCoords(); + float mean = getMeanAtOutCoords(); + float variance = getVarianceAtOutCoords(); + float offset = ${a}; + float scale = ${l}; + float inv = scale * inversesqrt(variance + float(${o})); + setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1))); + } + `}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class rX{constructor(e,t,s,r,i,o){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],pt(e,t),pt(e,s);let a="vec4(0.0)";r!=null&&(pt(e,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let l="vec4(1.0)";i!=null&&(pt(e,i),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=` + void main() { + vec4 offset = ${a}; + vec4 scale = ${l}; + + vec4 x = getXAtOutCoords(); + vec4 mean = getMeanAtOutCoords(); + vec4 variance = getVarianceAtOutCoords(); + + vec4 inv = scale * inversesqrt(variance + vec4(${o})); + + setOutput((x - mean) * inv + offset); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iX=({inputs:n,backend:e,attrs:t})=>{const{x:s,mean:r,variance:i,offset:o,scale:a}=n;N(r.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),N(o==null||r.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),N(a==null||r.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=t;l==null&&(l=.001);const c=[s,r,i];let u=null;o!=null&&(u=o.shape,c.push(o));let h=null;a!=null&&(h=a.shape,c.push(a));const d=oe().getBool("WEBGL_PACK_NORMALIZATION")?new rX(s.shape,r.shape,i.shape,u,h,l):new sX(s.shape,r.shape,i.shape,u,h,l);return e.runWebGLProgram(d,c,c[0].dtype)},oX={kernelName:vd,backendName:"webgl",kernelFunc:iX};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let aX=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=an(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const s=lX(this.rank);let r;const i=e.map((o,a)=>`sourceLoc.${_x[a]} = start[${a}] + coords.${_x[a]};`);r=` + ${t} sourceLoc; + ${t} coords = getOutputCoords(); + ${i.join(` +`)} + `,this.userCode=` + void main() { + ${r} + setOutput(getSource(${s})); + } + `}};const _x=["x","y","z","w","u","v"];function lX(n){if(n===1)return"sourceLoc";if(n<=6)return _x.slice(0,n).map(e=>"sourceLoc."+e).join(",");throw Error(`Slicing for rank ${n} is not yet supported`)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class cX{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const t=an(this.rank),s=Os("coords",this.rank),r=Os("sourceLoc",this.rank),i=this.rank===1?"sourceLoc":`vec2(${r.slice(-2).join()})`,o=`getChannel(getSource(${r.join()}), ${i})`,a=` + result.x = ${o}; + if (++${s[this.rank-1]} < ${e[this.rank-1]}) { + ++${r[this.rank-1]}; + result.y = ${o}; + --${r[this.rank-1]}; + } + `,l=this.rank===1?"":` + --${s[this.rank-1]}; + if (++${s[this.rank-2]} < ${e[this.rank-2]}) { + ++${r[this.rank-2]}; + result.z = ${o}; + if (++${s[this.rank-1]} < ${e[this.rank-1]}) { + ++${r[this.rank-1]}; + result.w = ${o}; + } + } + `,c=this.rank<=4?`sourceLoc = coords + + ${t}(${e.map((u,h)=>`start[${h}]`).join()});`:e.map((u,h)=>`${r[h]} = ${s[h]} + start[${h}];`).join(` +`);this.userCode=` + void main() { + ${t} coords = getOutputCoords(); + ${t} sourceLoc; + ${c} + vec4 result = vec4(0.); + ${a} + ${l} + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function uX(n,e,t,s){const r=s.texData.get(n.dataId),i=s.makeTensorInfo(t,n.dtype),o=s.texData.get(i.dataId);Object.assign(o,r),o.refCount=1,o.shape=t,o.dtype=n.dtype;let a=y4(e,it(n.shape));r.slice&&(a+=r.slice.flatOffset),o.slice={flatOffset:a,origDataId:r.slice&&r.slice.origDataId||n.dataId};const l=s.dataRefCount.get(o.slice.origDataId)||1;return s.dataRefCount.set(o.slice.origDataId,l+1),i}function sh(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{begin:i,size:o}=s,[a,l]=vm(r,i,o);if(hv(r,a,l),re(l)===0)return t.makeTensorInfo(l,r.dtype,[]);if(t.shouldExecuteOnCPU([r])||r.dtype==="string"){const h=t.texData.get(r.dataId),d=nH(h.values,a,l,r.shape,r.dtype);return t.makeTensorInfo(l,r.dtype,d)}const{isPacked:c}=t.texData.get(r.dataId),u=b4(r.shape,a,l);if(c||!u){const h=oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new cX(l):new aX(l),d=[a];return t.runWebGLProgram(h,[r],r.dtype,d)}return t.uploadToGPU(r.dataId),uX(r,a,l,t)}const hX={kernelName:Xd,backendName:"webgl",kernelFunc:sh};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dX=n=>{const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{blockShape:i,crops:o}=s;N(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const a=i.reduce((v,b)=>v*b),l=Dl(r.shape,i,a),c=Pl(l.length,i.length),u=Ll(r.shape,i,a),h=Sm(o,i.length),d=Cm(u,o,i.length),p=[],f=Be({inputs:{x:r},backend:t,attrs:{shape:l}}),x=Us({inputs:{x:f},backend:t,attrs:{perm:c}}),m=Be({inputs:{x},backend:t,attrs:{shape:u}}),g=sh({inputs:{x:m},backend:t,attrs:{begin:h,size:d}});return p.push(f),p.push(x),p.push(m),p.forEach(v=>t.disposeIntermediateTensorInfo(v)),g},pX={kernelName:ad,backendName:"webgl",kernelFunc:dX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fX(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,weights:i}=e,{size:o}=s,a=t.readSync(r.dataId),l=t.readSync(i.dataId),c=RE(a,l,i.dtype,i.shape,o);return t.makeTensorInfo([o],i.dtype,c)}const mX={kernelName:I0,backendName:"webgl",kernelFunc:fX};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gX=` + int r = int(a.r) & int(b.r); + int g = int(a.g) & int(b.g); + int rb = int(a.b) & int(b.b); + int ra = int(a.a) & int(b.a); + return vec4(r, g, rb, ra); +`,xX=` + return float(int(a.r) & int(b.r)); +`;function vX(n){const{inputs:e,backend:t}=n,{a:s,b:r}=e,i=oe().getBool("WEBGL_PACK_BINARY_OPERATIONS"),o=oe().getNumber("WEBGL_VERSION");if(t.shouldExecuteOnCPU([s,r])||o===1){const l=t.texData.get(s.dataId).values,c=t.texData.get(r.dataId).values,[u,h]=IG(s.shape,r.shape,l,c,s.dtype),d=t.makeTensorInfo(h,s.dtype),p=t.texData.get(d.dataId);return p.values=u,d}let a;return i?a=new th(gX,s.shape,r.shape,!1):a=new _l(xX,s.shape,r.shape),t.runWebGLProgram(a,[s,r],s.dtype)}const bX={kernelName:c2,backendName:"webgl",kernelFunc:vX};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yX(n){const{inputs:e,backend:t}=n,{s0:s,s1:r}=e,i=t.readSync(s.dataId),o=t.readSync(r.dataId),a=pt(Array.from(i),Array.from(o));return t.makeTensorInfo([a.length],"int32",Int32Array.from(a))}const wX={kernelName:u2,backendName:"webgl",kernelFunc:yX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const SX="return float(a != b);",GE=_s({opSnippet:SX,cpuKernelImpl:XG,dtype:"bool"}),CX={kernelName:Pd,backendName:"webgl",kernelFunc:GE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bp(n){const{inputs:e,backend:t}=n,{input:s}=e,r=t.texData.get(s.dataId);return vr({inputs:{x:r.complexTensorInfos.real},backend:t})}const _X={kernelName:Y0,backendName:"webgl",kernelFunc:bp};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const TX="return float(int(x));";function IX(n,e){const t=new Vi(n.shape,TX),s=e.runWebGLProgram(t,[n],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Tx(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{dtype:i}=s;if(i==="complex64"){if(r.dtype==="complex64")return vr({inputs:{x:r},backend:t});const o=On(r.shape),a=Tx({inputs:{x:r},backend:t,attrs:{dtype:"float32"}}),l=ka({inputs:{real:a,imag:o},backend:t});return o.dispose(),t.disposeIntermediateTensorInfo(a),l}if(r.dtype==="complex64"){const o=bp({inputs:{input:r},backend:t}),a=Tx({inputs:{x:o},backend:t,attrs:{dtype:i}});return t.disposeIntermediateTensorInfo(o),a}if(!i2(r.dtype,i)){const o=vr({inputs:{x:r},backend:t});return{dataId:o.dataId,shape:o.shape,dtype:i}}if(t.shouldExecuteOnCPU([r])){const o=t.texData.get(r.dataId).values,[a,l,c]=EG(o,r.shape,r.dtype,i);return t.makeTensorInfo(a,l,c)}if(i==="int32")return IX(r,t);if(i==="bool"){const o=t.makeTensorInfo([],"bool",hs("bool",1)),l=GE({inputs:{a:r,b:o},backend:t});return t.disposeIntermediateTensorInfo(o),l}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${i}`)}const EX={kernelName:su,backendName:"webgl",kernelFunc:Tx};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dw="return ceil(x);",kX=Kt({opSnippet:dw,packedOpSnippet:dw,cpuKernelImpl:kG}),AX={kernelName:ru,backendName:"webgl",kernelFunc:kX};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let RX=class{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=` + + void main() { + float value = getAAtOutCoords(); + if (isnan(value)) { + setOutput(value); + return; + } + + setOutput(clamp(value, minVal, maxVal)); + } + `}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class MX{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=` + void main() { + vec4 value = getAAtOutCoords(); + + if (any(isnan(value))) { + setOutput(value); + return; + } + + setOutput(clamp(value, vec4(minVal), vec4(maxVal))); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function NX(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{clipValueMin:i,clipValueMax:o}=s;let a;oe().getBool("WEBGL_PACK_CLIP")?a=new MX(r.shape):a=new RX(r.shape);const l=[[i],[o]];return t.runWebGLProgram(a,[r],r.dtype,l)}const $X={kernelName:iu,backendName:"webgl",kernelFunc:NX};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let DX=class{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=` + void main() { + float re = abs(getRealAtOutCoords()); + float im = abs(getImagAtOutCoords()); + float mx = max(re, im); + + // sadly the length function in glsl is not underflow-safe + // (at least not on Intel GPUs). So the safe solution is + // to ensure underflow-safety in all cases. + setOutput( + mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx)) + ); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pw(n,e){return{dataId:e.dataId,dtype:e.dtype,shape:n.shape}}function PX(n){const{inputs:e,backend:t}=n,{x:s}=e,r=t.texData.get(s.dataId),i=new DX(s.shape),o=[pw(s,r.complexTensorInfos.real),pw(s,r.complexTensorInfos.imag)];return t.runWebGLProgram(i,o,o[0].dtype)}const LX={kernelName:ld,backendName:"webgl",kernelFunc:PX};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let FX=class{constructor(e){this.outputShape=[],this.outputShape=nr(e,1),this.variableNames=e.map((o,a)=>`T${a}`);const t=new Array(e.length-1);t[0]=e[0][1];for(let o=1;o`T${m}`);const l=new Array(e.length-1);l[0]=e[0][t];for(let x=1;x= ${l[x-1]}) { + return getChannel( + getT${x}(${Wp(a,c,m)}), + vec2(${Wp(u,c,m)})); + }`}const p=l.length,f=l[l.length-1];d+=` + return getChannel( + getT${p}(${Wp(a,c,f)}), + vec2(${Wp(u,c,f)}));`,this.userCode=` + float getValue(${a.map(x=>"int "+x)}) { + ${d} + } + + void main() { + ${i} coords = getOutputCoords(); + vec4 result = vec4(getValue(${o}), 0., 0., 0.); + + ${o[r-1]} = ${o[r-1]} + 1; + if (${o[r-1]} < ${s[r-1]}) { + result.g = getValue(${o}); + } + + ${o[r-2]} = ${o[r-2]} + 1; + if (${o[r-2]} < ${s[r-2]}) { + result.a = getValue(${o}); + } + + ${o[r-1]} = ${o[r-1]} - 1; + if (${o[r-2]} < ${s[r-2]} && + ${o[r-1]} < ${s[r-1]}) { + result.b = getValue(${o}); + } + setOutput(result); + } + `}}function Wp(n,e,t){const s=n.indexOf(e);return n.map((i,o)=>o===s?`${i} - ${t}`:i).join()}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Jm(n){const{inputs:e,backend:t}=n,{input:s}=e,r=t.texData.get(s.dataId);return vr({inputs:{x:r.complexTensorInfos.imag},backend:t})}const zX={kernelName:W0,backendName:"webgl",kernelFunc:Jm};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kh(n,e,t){const s=n[0].dtype;if(s==="complex64"){const p=n.map(v=>bp({inputs:{input:v},backend:t})),f=n.map(v=>Jm({inputs:{input:v},backend:t})),x=kh(p,e,t),m=kh(f,e,t),g=ka({inputs:{real:x,imag:m},backend:t});return p.forEach(v=>t.disposeIntermediateTensorInfo(v)),f.forEach(v=>t.disposeIntermediateTensorInfo(v)),t.disposeIntermediateTensorInfo(x),t.disposeIntermediateTensorInfo(m),g}let r=t.shouldExecuteOnCPU(n);if(s==="string"&&(r=!0),r){const p=n.map(y=>{const C=[-1,re(y.shape.slice(e))];return Be({inputs:{x:y},backend:t,attrs:{shape:C}})}),f=p.map(y=>({vals:t.readSync(y.dataId),shape:y.shape})),x=nr(p.map(y=>y.shape),1),m=p[0].shape[0]===1,g=AG(f,x,s,m),v=nr(n.map(y=>y.shape),e),b=t.makeTensorInfo(v,s,g);return p.forEach(y=>t.disposeIntermediateTensorInfo(y)),b}const i=n.filter(p=>re(p.shape)>0),o=oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&i[0].shape.length>1;if(i.length===1){const p=o?new Vi(n[0].shape,qo):new Yo(n[0].shape,qo);return t.runWebGLProgram(p,n,s)}const a=oe().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(i.length>a){const p=[];for(let x=0;xf.shape),e);return t.runWebGLProgram(p,i,s)}const{tensors2D:l,outShape:c}=BX(i,e,t),u=new FX(l.map(p=>p.shape)),h=t.runWebGLProgram(u,l,s);l.forEach(p=>t.disposeIntermediateTensorInfo(p));const d=Be({inputs:{x:h},attrs:{shape:c},backend:t});return t.disposeIntermediateTensorInfo(h),d}function BX(n,e,t){const s=nr(n.map(i=>i.shape),e);return{tensors2D:n.map(i=>Be({inputs:{x:i},attrs:{shape:[-1,re(i.shape.slice(e))]},backend:t})),outShape:s}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function HE(n){const{inputs:e,backend:t,attrs:s}=n,{axis:r}=s,i=It(r,e[0].shape)[0],o=e.map(c=>c.shape);bm(o,i);const a=nr(e.map(c=>c.shape),i);if(re(a)===0)return t.makeTensorInfo(a,e[0].dtype,[]);const l=e.filter(c=>re(c.shape)>0);return l.length===1?vr({inputs:{x:l[0]},backend:t}):kh(l,i,t)}const UX={kernelName:cd,backendName:"webgl",kernelFunc:HE};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class qE{constructor(e,t=!1,s=null,r=!1,i=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const o=e.padInfo.top,a=e.padInfo.left,l=e.strideHeight,c=e.strideWidth,u=e.dilationHeight,h=e.dilationWidth,d=e.filterHeight,p=e.filterWidth,f=Math.floor(e.inChannels/4)*4,x=e.inChannels%4,m=e.dataFormat==="channelsLast",g=m?1:2,v=m?2:3,b=m?3:1;let y="",w="";s&&(r?y=`float activation(float a) { + float b = getPreluActivationWeightsAtOutCoords(); + ${s} + }`:i?y=`float activation(float a) { + float b = getLeakyreluAlphaAtOutCoords(); + ${s} + }`:y=` + float activation(float x) { + ${s} + } + `,w="result = activation(result);");const C=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),i&&this.variableNames.push("leakyreluAlpha"),this.userCode=` + ${y} + + const ivec2 strides = ivec2(${l}, ${c}); + const ivec2 pads = ivec2(${o}, ${a}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d2 = coords[${b}]; + + ivec2 xRCCorner = + ivec2(coords[${g}], coords[${v}]) * strides - pads; + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${d}; wR++) { + int xR = xRCorner + wR * ${u}; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${p}; wC++) { + int xC = xCCorner + wC * ${h}; + + if (xC < 0 || xC >= ${e.inWidth}) { + continue; + } + + for (int d1 = 0; d1 < ${f}; d1 += 4) { + vec4 wValues = vec4( + getW(wR, wC, d1, d2), + getW(wR, wC, d1 + 1, d2), + getW(wR, wC, d1 + 2, d2), + getW(wR, wC, d1 + 3, d2) + ); + + if (${m}) { + vec4 xValues = vec4( + getX(batch, xR, xC, d1), + getX(batch, xR, xC, d1 + 1), + getX(batch, xR, xC, d1 + 2), + getX(batch, xR, xC, d1 + 3) + ); + dotProd += dot(xValues, wValues); + } else { + vec4 xValues = vec4( + getX(batch, d1, xR, xC), + getX(batch, d1 + 1, xR, xC), + getX(batch, d1 + 2, xR, xC), + getX(batch, d1 + 3, xR, xC) + ); + dotProd += dot(xValues, wValues); + } + } + + if (${x===1}) { + + if (${m}) { + dotProd += + getX(batch, xR, xC, ${f}) * + getW(wR, wC, ${f}, d2); + } else { + dotProd += + getX(batch, ${f}, xR, xC) * + getW(wR, wC, ${f}, d2); + } + + } else if (${x===2}) { + vec2 wValues = vec2( + getW(wR, wC, ${f}, d2), + getW(wR, wC, ${f} + 1, d2) + ); + + if (${m}) { + vec2 xValues = vec2( + getX(batch, xR, xC, ${f}), + getX(batch, xR, xC, ${f} + 1) + ); + dotProd += dot(xValues, wValues); + } else { + vec2 xValues = vec2( + getX(batch, ${f}, xR, xC), + getX(batch, ${f} + 1, xR, xC) + ); + dotProd += dot(xValues, wValues); + } + + } else if (${x===3}) { + vec3 wValues = vec3( + getW(wR, wC, ${f}, d2), + getW(wR, wC, ${f} + 1, d2), + getW(wR, wC, ${f} + 2, d2) + ); + + if (${m}) { + vec3 xValues = vec3( + getX(batch, xR, xC, ${f}), + getX(batch, xR, xC, ${f} + 1), + getX(batch, xR, xC, ${f} + 2) + ); + dotProd += dot(xValues, wValues); + } else { + vec3 xValues = vec3( + getX(batch, ${f}, xR, xC), + getX(batch, ${f} + 1, xR, xC), + getX(batch, ${f} + 2, xR, xC) + ); + dotProd += dot(xValues, wValues); + } + + } + } + } + + float result = dotProd; + ${C} + ${w} + setOutput(result); + } + `}}class VX{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,s=e.padInfo.top,r=e.padInfo.left,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,l=e.dilationDepth,c=e.dilationHeight,u=e.dilationWidth,h=e.filterDepth,d=e.filterHeight,p=e.filterWidth,f=Math.floor(e.inChannels/4)*4,x=e.inChannels%4;this.userCode=` + const ivec3 strides = ivec3(${i}, ${o}, ${a}); + const ivec3 pads = ivec3(${t}, ${s}, ${r}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int d2 = coords.u; + + ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; + int xFCorner = xFRCCorner.x; + int xRCorner = xFRCCorner.y; + int xCCorner = xFRCCorner.z; + + // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get + // y(yF, yR, yC, d2). ? = to be determined. : = across all + // values in that axis. + float dotProd = 0.0; + for (int wF = 0; wF < ${h}; wF++) { + int xF = xFCorner + wF * ${l}; + + if (xF < 0 || xF >= ${e.inDepth}) { + continue; + } + + for (int wR = 0; wR < ${d}; wR++) { + int xR = xRCorner + wR * ${c}; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${p}; wC++) { + int xC = xCCorner + wC * ${u}; + + if (xC < 0 || xC >= ${e.inWidth}) { + continue; + } + + for (int d1 = 0; d1 < ${f}; d1 += 4) { + vec4 xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3) + ); + vec4 wValues = vec4( + getW(wF, wR, wC, d1, d2), + getW(wF, wR, wC, d1 + 1, d2), + getW(wF, wR, wC, d1 + 2, d2), + getW(wF, wR, wC, d1 + 3, d2) + ); + + dotProd += dot(xValues, wValues); + } + + if (${x===1}) { + dotProd += + getX(batch, xF, xR, xC, ${f}) * + getW(wF, wR, wC, ${f}, d2); + } else if (${x===2}) { + vec2 xValues = vec2( + getX(batch, xF, xR, xC, ${f}), + getX(batch, xF, xR, xC, ${f} + 1) + ); + vec2 wValues = vec2( + getW(wF, wR, wC, ${f}, d2), + getW(wF, wR, wC, ${f} + 1, d2) + ); + dotProd += dot(xValues, wValues); + } else if (${x===3}) { + vec3 xValues = vec3( + getX(batch, xF, xR, xC, ${f}), + getX(batch, xF, xR, xC, ${f} + 1), + getX(batch, xF, xR, xC, ${f} + 2) + ); + vec3 wValues = vec3( + getW(wF, wR, wC, ${f}, d2), + getW(wF, wR, wC, ${f} + 1, d2), + getW(wF, wR, wC, ${f} + 2, d2) + ); + dotProd += dot(xValues, wValues); + } + } + } + } + setOutput(dotProd); + } + `}}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class XE{constructor(e,t=!1,s=null,r=!1,i=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Ns(this.outputShape.length);const o=e.padInfo.left,a=e.strideWidth,l=e.dilationWidth,c=e.filterHeight,u=e.filterWidth,h=u;let d=` + int xR; int xC; int xCOffset; + vec4 wTexel; vec4 previous; vec4 final;`;for(let m=0;m=0 && xR < inDims[0]) { + `;for(let m=0;m<(h+1)/2;m++){const g=m*2;if(d+=` + xC = xCCorner + ${g*l}; + `,a===1){if(g= 0 && xCOffset < inDims[1] && xTexelC${g}Ready == 0) { + xTexelC${g} = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${g}.zw = vec2(0.0); + } + xTexelC${g}Ready = 1; + } + `,l===1&&g>0?d+=` + xC${g} = vec4(xTexelC${g-2}.zw, xTexelC${g}.xy); + `:d+=` + xCOffset = xC + 1 - 2; + + if (xCOffset >= 0 && xCOffset < inDims[1]) { + previous = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + previous.zw = vec2(0.0); + } + + xC${g} = vec4(previous.zw, xTexelC${g}.xy); + } else { + xC${g} = vec4(0.0, 0.0, xTexelC${g}.xy); + } + `):d+=` + if (xC >= 0 && xC < inDims[1] && xTexelC${g}Ready == 0) { + xTexelC${g} = getX(batch, xR, xC, d1); + if (xC + 1 >= inDims[1]) { + xTexelC${g}.zw = vec2(0.0); + } + xTexelC${g}Ready = 1; + } + + xC${g} = xTexelC${g}; + `,g+1= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) { + xTexelC${g+1} = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${g+1}.zw = vec2(0.0); + } + xTexelC${g+1}Ready = 1; + } + `,l>1?d+=` + xCOffset -= 2; + if (xCOffset >= 0 && xCOffset < inDims[1]) { + previous = getX(batch, xR, xCOffset, d1); + xC${g+1} = vec4(previous.zw, xTexelC${g+1}.xy); + } else { + xC${g+1} = vec4(0.0, 0.0, xTexelC${g+1}.xy); + } + `:d+=` + xC${g+1} = vec4(xTexelC${g}.zw, xTexelC${g+1}.xy); + `):v===1?d+=` + xC${g+1} = xTexelC${g}; + `:d+=` + xCOffset = xC + ${v}; + + if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) { + xTexelC${g+1} = getX(batch, xR, xCOffset, d1); + if (xCOffset + 1 >= inDims[1]) { + xTexelC${g+1}.zw = vec2(0.0); + } + xTexelC${g+1}Ready = 1; + } + + xC${g+1} = xTexelC${g+1}; + `}}else g= 0 && xCOffset < inDims[1] && xTexelC${g}Ready == 0) { + xTexelC${g} = getX(batch, xR, xCOffset, d1); + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${g}.zw = vec2(0.0); + } + xTexelC${g}Ready = 1; + } + + if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${g+1}Ready == 0) { + xTexelC${g+1} = getX(batch, xR, xC + 1, d1); + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xC + 2 >= inDims[1]) { + xTexelC${g+1}.zw = vec2(0.0); + } + xTexelC${g+1}Ready = 1; + } + + xC${g} = vec4(xTexelC${g}.zw, xTexelC${g+1}.zw); + `,g+1= 0 && xCOffset < inDims[1]) { + final = getX(batch, xR, xCOffset, d1); + } + xC${g+1} = vec4(xTexelC${g+1}.xy, final.xy); + `)):(d+=` + if(xC >= 0 && xC < inDims[1] && xTexelC${g}Ready == 0) { + xTexelC${g} = getX(batch, xR, xC, d1); + if (xC + 1 >= inDims[1]) { + xTexelC${g}.zw = vec2(0.0); + } + xTexelC${g}Ready = 1; + } + + xCOffset = xC + strides[1]; + if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) { + xTexelC${g+1} = getX(batch, xR, xCOffset, d1); + if (xCOffset + 1 >= inDims[1]) { + xTexelC${g+1}.zw = vec2(0.); + } + xTexelC${g+1}Ready = 1; + } + + xC${g} = vec4( + xTexelC${g}.xy, xTexelC${g+1}.xy); + `,g+1= 0) { + // Use custom imod instead mod. On Intel GPU, mod may generate + // unexpected value. + // https://github.com/tensorflow/tfjs/issues/5447 + offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1]; + d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) / + inChannels); + + if(d1 < inputShape[${a}] && d1 >= 0) { + + ch = imod(pos, inChannels); + + if (${i}) { + innerDims = vec2(d1, ch); + result[${u*2+h}] = getChannel( + getA(rc.x, d0, int(innerDims.x), + int(innerDims.y)), innerDims); + } else { + innerDims = vec2(d0, d1); + result[${u*2+h}] = getChannel( + getA(rc.x, ch, int(innerDims.x), + int(innerDims.y)), innerDims); + } + } + } + } + `;this.userCode=` + void main() { + ivec3 rc = getOutputCoords(); + + vec4 result = vec4(0); + + int blockIndex, pos, offsetY, d0, offsetX, d1, ch; + vec2 innerDims; + + ${c} + + ${r.output} = result; + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function n0(n,e){const t=n.length;return t>=3?e?[...n.slice(0,-3),n[t-3]*n[t-2],n[t-1]]:[...n.slice(0,-3),n[t-3],n[t-2]*n[t-1]]:!e&&t===1&&n[0]>1?[n[0],1]:null}function KE({x:n,filter:e,convInfo:t,backend:s,bias:r=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:a=null}){const l=n.shape,c=s.texData.get(n.dataId),u=t.inChannels,h=l[0]*l[1]*l[2],d=t.outChannels,p=t.dataFormat==="channelsLast",f=!1,x=!1;let m;const g=[];if(i!=null){const y=n0(i.shape,p);y!=null&&(i=Be({inputs:{x:i},backend:s,attrs:{shape:y}}),g.push(i))}if(r!=null){const y=n0(r.shape,p);y!=null&&(r=Be({inputs:{x:r},backend:s,attrs:{shape:y}}),g.push(r))}if(!((h===1||d===1)&&u>BE)&&c.isPacked&&p&&c.texture!=null&&l[2]%2!==0&&Wt(c.shape.slice(-3),l.slice(-3))){const y=l[0]*l[1]*(l[2]+1),w={dataId:n.dataId,shape:[1,y,t.inChannels],dtype:n.dtype},C=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,N(e0(c.shape,w.shape),()=>`packed reshape ${c.shape} to ${w.shape} isn't free`);const T=Be({inputs:{x:e},backend:s,attrs:{shape:[1,t.inChannels,t.outChannels]}});g.push(T);const E=t0({a:w,b:T,backend:s,transposeA:f,transposeB:x,bias:r,activation:a,preluActivationWeights:i,leakyreluAlpha:o}),R=s.texData.get(E.dataId);N(R.isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=C,R.shape=t.outShape,m=vr({inputs:{x:E},backend:s}),m.shape=t.outShape,g.push(E)}else{const y=t.outHeight*t.outWidth,w=Be({inputs:{x:n},backend:s,attrs:{shape:p?[t.batchSize,y,t.inChannels]:[t.batchSize,t.inChannels,y]}}),C=Be({inputs:{x:e},backend:s,attrs:{shape:[1,t.inChannels,t.outChannels]}}),T=t0({a:p?w:C,b:p?C:w,transposeA:!p,transposeB:x,backend:s,bias:r,activation:a,preluActivationWeights:i,leakyreluAlpha:o});m=Be({inputs:{x:T},backend:s,attrs:{shape:t.outShape}}),g.push(w),g.push(C),g.push(T)}for(const y of g)s.disposeIntermediateTensorInfo(y);return m}function jE({x:n,filter:e,convInfo:t,backend:s,bias:r=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:a=null}){const{filterWidth:l,filterHeight:c,inChannels:u,outWidth:h,outHeight:d,dataFormat:p}=t,f=p==="channelsLast",x=l*c*u,m=d*h,g=[t.batchSize,x,m],v=!0,b=!1,y=[];if(i!=null){const U=n0(i.shape,f);U!=null&&(i=Be({inputs:{x:i},backend:s,attrs:{shape:U}}),y.push(i))}if(r!=null){const U=n0(r.shape,f);U!=null&&(r=Be({inputs:{x:r},backend:s,attrs:{shape:U}}),y.push(r))}const w=Be({inputs:{x:e},backend:s,attrs:{shape:[1,x,re(e.shape)/x]}});y.push(w);const C=new WX(g,t),T=[n.shape,[t.padInfo.top,t.padInfo.left],[t.strideHeight,t.strideWidth],[t.dilationHeight,t.dilationWidth],[t.inChannels],[t.filterWidth*t.inChannels],[t.outWidth]],E=s.runWebGLProgram(C,[n],"float32",T),R=Be({inputs:{x:E},backend:s,attrs:{shape:g}});y.push(E),y.push(R);const _=r!=null,k=i!=null,F=a==="leakyrelu",B=a?Xh(a,!0):null,M=new zE(f?R.shape:w.shape,f?w.shape:R.shape,f?[t.batchSize,m,t.outChannels]:[t.batchSize,t.outChannels,m],v,b,_,B,k,F),P=f?[R,w]:[w,R];if(r&&P.push(r),k&&P.push(i),F){const U=s.makeTensorInfo([],"float32",ya(o,"float32"));P.push(U),y.push(U)}const L=s.runWebGLProgram(M,P,"float32"),q=Be({inputs:{x:L},backend:s,attrs:{shape:t.outShape}});y.push(L);for(const U of y)s.disposeIntermediateTensorInfo(U);return q}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function GX(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:i}=e,{strides:o,pad:a,dataFormat:l,dilations:c,dimRoundingMode:u}=s,h=wr(l),d=Cn(r.shape,i.shape,o,c,a,u,!1,h);let p;if(d.filterHeight===1&&d.filterWidth===1&&d.dilationHeight===1&&d.dilationWidth===1&&d.strideHeight===1&&d.strideWidth===1&&(d.padInfo.type==="SAME"||d.padInfo.type==="VALID"))p=KE({x:r,filter:i,convInfo:d,backend:t});else if(d.strideWidth<=2&&h==="channelsLast"&&oe().getBool("WEBGL_EXP_CONV")){const x=new XE(d),m=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];p=t.runWebGLProgram(x,[r,i],"float32",m)}else if(oe().getBool("WEBGL_CONV_IM2COL"))p=jE({x:r,filter:i,convInfo:d,backend:t});else{const x=new qE(d);p=t.runWebGLProgram(x,[r,i],"float32")}const f=Be({inputs:{x:p},backend:t,attrs:{shape:d.outShape}});return t.disposeIntermediateTensorInfo(p),f}const HX={kernelName:ud,backendName:"webgl",kernelFunc:GX};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let qX=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,s=e.strideWidth,r=e.padInfo.top,i=e.padInfo.left,o=e.dataFormat==="channelsLast";this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int wR = coords.x; + int wC = coords.y; + int d1 = coords.z; + int d2 = coords.w; + + // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + + for (int b = 0; b < ${e.batchSize}; b++) { + for (int yR = 0; yR < ${e.outHeight}; yR++) { + int xR = wR + yR * ${t} - ${r}; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int yC = 0; yC < ${e.outWidth}; yC++) { + int xC = wC + yC * ${s} - ${i}; + + if (xC < 0 || xC >= ${e.inWidth}) { + continue; + } + + ${o?`float dyValue = getDy(b, yR, yC, d2); + float xValue = getX(b, xR, xC, d1); + dotProd += (xValue * dyValue);`:`float dyValue = getDy(b, d2, yR, yC); + float xValue = getX(b, d1, xR, xC); + dotProd += (xValue * dyValue);`} + } + } + } + setOutput(dotProd); + } + `}},XX=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,r=e.strideHeight,i=e.strideWidth,o=e.dataFormat==="channelsLast",a=t-1-e.padInfo.top,l=s-1-e.padInfo.left,c=o?1:2,u=o?2:3,h=o?3:1;this.userCode=` + const ivec2 pads = ivec2(${a}, ${l}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d1 = coords[${h}]; + + ivec2 dyCorner = ivec2(coords[${c}], coords[${u}]) - pads; + int dyRCorner = dyCorner.x; + int dyCCorner = dyCorner.y; + + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${t}; wR++) { + float dyR = float(dyRCorner + wR) / ${r}.0; + + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = ${t} - 1 - wR; + + for (int wC = 0; wC < ${s}; wC++) { + float dyC = float(dyCCorner + wC) / ${i}.0; + + if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = ${s} - 1 - wC; + + for (int d2 = 0; d2 < ${e.outChannels}; d2++) { + + if (${o}) { + float xValue = getDy(batch, idyR, idyC, d2); + float wValue = getW(wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } else { + float xValue = getDy(batch, d2, idyR, idyC); + float wValue = getW(wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } + + } + } + } + setOutput(dotProd); + } + `}},KX=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,s=e.strideHeight,r=e.strideWidth,i=e.padInfo.front,o=e.padInfo.top,a=e.padInfo.left;this.userCode=` + void main() { + ivec5 coords = getOutputCoords(); + int wF = coords.x; + int wR = coords.y; + int wC = coords.z; + int d1 = coords.w; + int d2 = coords.u; + + float dotProd = 0.0; + + for (int b = 0; b < ${e.batchSize}; b++) { + for (int yF = 0; yF < ${e.outDepth}; yF++) { + int xF = wF + yF * ${t} - ${i}; + + if (xF < 0 || xF >= ${e.inDepth}) { + continue; + } + + for (int yR = 0; yR < ${e.outHeight}; yR++) { + int xR = wR + yR * ${s} - ${o}; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int yC = 0; yC < ${e.outWidth}; yC++) { + int xC = wC + yC * ${r} - ${a}; + + if (xC < 0 || xC >= ${e.inWidth}) { + continue; + } + + float dyValue = getDy(b, yF, yR, yC, d2); + float xValue = getX(b, xF, xR, xC, d1); + dotProd += (xValue * dyValue); + } + } + } + } + setOutput(dotProd); + } + `}},jX=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,s=e.filterHeight,r=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,l=t-1-e.padInfo.front,c=s-1-e.padInfo.top,u=r-1-e.padInfo.left;this.userCode=` + const ivec3 pads = ivec3(${l}, ${c}, ${u}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int d1 = coords.u; + + + ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; + int dyFCorner = dyCorner.x; + int dyRCorner = dyCorner.y; + int dyCCorner = dyCorner.z; + + float dotProd = 0.0; + for (int wF = 0; wF < ${t}; wF++) { + float dyF = float(dyFCorner + wF) / ${i}.0; + + if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) { + continue; + } + int idyF = int(dyF); + + int wFPerm = ${t} - 1 - wF; + + for (int wR = 0; wR < ${s}; wR++) { + float dyR = float(dyRCorner + wR) / ${o}.0; + + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = ${s} - 1 - wR; + + for (int wC = 0; wC < ${r}; wC++) { + float dyC = float(dyCCorner + wC) / ${a}.0; + + if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = ${r} - 1 - wC; + + for (int d2 = 0; d2 < ${e.outChannels}; d2++) { + float xValue = getDy(batch, idyF, idyR, idyC, d2); + float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } + } + } + } + setOutput(dotProd); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function YX(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,dy:i}=e,{strides:o,pad:a,dataFormat:l,dimRoundingMode:c,filterShape:u}=s,h=wr(l),d=Cn(r.shape,u,o,1,a,c,!1,h),p=new qX(d);return t.runWebGLProgram(p,[r,i],"float32")}const ZX={kernelName:k0,backendName:"webgl",kernelFunc:YX};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class JX{constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=Ns(this.outputShape.length);const t=e.filterHeight,s=e.filterWidth,r=t-1-e.padInfo.top,i=s-1-e.padInfo.left;this.userCode=` + const ivec2 pads = ivec2(${r}, ${i}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d1 = coords[3]; + + ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads; + int dyRCorner = dyCorner.x; + int dyCCorner = dyCorner.y; + + vec4 result = vec4(0.); + for (int wR = 0; wR < ${t}; wR++) { + float dyR = float(dyRCorner + wR) / strides[0]; + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + int wRPerm = ${t} - 1 - wR; + + for (int wC = 0; wC < ${s}; wC++) { + int wCPerm = ${s} - 1 - wC; + + float dyC = float(dyCCorner + wC) / strides[1]; + bool idyCVal = (dyC >= 0.0) && (dyC < ${e.outWidth}.0) + && (fract(dyC) == 0.0); + int idyC = int(dyC); + + float dyC2 = float(dyCCorner + wC + 1) / strides[1]; + bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0) + && (fract(dyC2) == 0.0); + int idyC2 = int(dyC2); + + if (idyCVal && idyCVal2) { + for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) { + vec4 wValue = getW(wRPerm, wCPerm, d1, d2); + vec4 dySample = getDy(batch, idyR, idyC, d2); + vec4 dySample2 = (idyC / 2 == idyC2 / 2) ? + dySample : getDy(batch, idyR, idyC2, d2); + + vec2 dyValue = mod(float(idyC), 2.) == 0. ? + dySample.xy : dySample.zw; + result.xy += vec2(dot(dyValue, wValue.xy), + dot(dyValue, wValue.zw)); + + dyValue = mod(float(idyC2), 2.) == 0. ? + dySample2.xy : dySample2.zw; + result.zw += vec2(dot(dyValue, wValue.xy), + dot(dyValue, wValue.zw)); + } + } else if (idyCVal) { + for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) { + vec4 wValue = getW(wRPerm, wCPerm, d1, d2); + vec4 dySample = getDy(batch, idyR, idyC, d2); + vec2 dyValue = mod(float(idyC), 2.) == 0. ? + dySample.xy : dySample.zw; + result.xy += vec2(dot(dyValue, wValue.xy), + dot(dyValue, wValue.zw)); + } + } else if (idyCVal2) { + for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) { + vec4 wValue = getW(wRPerm, wCPerm, d1, d2); + vec4 dySample = getDy(batch, idyR, idyC2, d2); + vec2 dyValue = mod(float(idyC2), 2.) == 0. ? + dySample.xy : dySample.zw; + result.zw += vec2(dot(dyValue, wValue.xy), + dot(dyValue, wValue.zw)); + } + } + } + } + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function QX(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,filter:i}=e,{inputShape:o,strides:a,pad:l,dataFormat:c,dimRoundingMode:u}=s,h=wr(c),d=Cn(o,i.shape,a,1,l,u,!1,h);if(oe().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&h==="channelsLast"){const p=[[d.strideHeight,d.strideWidth]],f=new JX(d);return t.runWebGLProgram(f,[r,i],"float32",p)}else{const p=new XX(d);return t.runWebGLProgram(p,[r,i],"float32")}}const eK={kernelName:hd,backendName:"webgl",kernelFunc:QX};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function tK(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:i}=e,{strides:o,pad:a,dilations:l}=s,c=Ri(r.shape,i.shape,o,l,a),u=new VX(c);return t.runWebGLProgram(u,[r,i],"float32")}const nK={kernelName:dd,backendName:"webgl",kernelFunc:tK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sK(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,dy:i}=e,{strides:o,pad:a,filterShape:l}=s,c=Ri(r.shape,l,o,1,a),u=new KX(c);return t.runWebGLProgram(u,[r,i],"float32")}const rK={kernelName:A0,backendName:"webgl",kernelFunc:sK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function iK(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,filter:i}=e,{pad:o,strides:a,inputShape:l}=s,c=Ri(l,i.shape,a,1,o),u=new jX(c);return t.runWebGLProgram(u,[r,i],"float32")}const oK={kernelName:R0,backendName:"webgl",kernelFunc:iK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const aK=nh+` + return cos(x); +`,lK=` + vec4 result = cos(x); + bvec4 isNaN = isnan(x); + ${Ul} + return result; +`,cK=Kt({opSnippet:aK,packedOpSnippet:lK}),uK={kernelName:ou,backendName:"webgl",kernelFunc:cK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hK=` + float e2x = exp(-x); + return (e2x + 1.0 / e2x) / 2.0; +`,dK=Kt({opSnippet:hK}),pK={kernelName:au,backendName:"webgl",kernelFunc:dK};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let fK=class{constructor(e,t,s,r,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[o,a,l,c]=e,[u]=t,[h,d]=s;this.outputShape=[u,h,d,c];const p=r==="bilinear"?1:0,[f,x]=[`${a-1}.0`,`${l-1}.0`],[m,g,v]=h>1?[`${(a-1)/(h-1)}`,"(y2-y1) * height_ratio",`y1*${f} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${f}`],[b,y,w]=d>1?[`${(l-1)/(d-1)}`,"(x2-x1) * width_ratio",`x1*${x} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${x}`];this.userCode=` + const float height_ratio = float(${m}); + const float width_ratio = float(${b}); + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int y = coords[1]; + int x = coords[2]; + int d = coords[3]; + + // get box vals + float y1 = getBoxes(b,0); + float x1 = getBoxes(b,1); + float y2 = getBoxes(b,2); + float x2 = getBoxes(b,3); + + // get image in batch index + int bInd = round(getBoxInd(b)); + if(bInd < 0 || bInd >= ${o}) { + return; + } + + float height_scale = ${g}; + float width_scale = ${y}; + + float in_y = ${v}; + if( in_y < 0.0 || in_y > ${f} ) { + setOutput(float(${i})); + return; + } + float in_x = ${w}; + if( in_x < 0.0 || in_x > ${x} ) { + setOutput(float(${i})); + return; + } + + vec2 sourceFracIndexCR = vec2(in_x,in_y); + if(${p} == 1) { + // Compute the four integer indices. + ivec2 sourceFloorCR = ivec2(sourceFracIndexCR); + ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR)); + + float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d); + float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d); + float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d); + float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d); + + vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR); + + float top = topLeft + (topRight - topLeft) * fracCR.x; + float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x; + float newValue = top + (bottom - top) * fracCR.y; + setOutput(newValue); + } else { + // Compute the coordinators of nearest neighbor point. + ivec2 sourceNearestCR = ivec2(floor( + sourceFracIndexCR + vec2(0.5,0.5))); + float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d); + setOutput(newValue); + } + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mK=n=>{const{inputs:e,backend:t,attrs:s}=n,{image:r,boxes:i,boxInd:o}=e,{cropSize:a,method:l,extrapolationValue:c}=s,u=new fK(r.shape,i.shape,a,l,c);return t.runWebGLProgram(u,[r,i,o],"float32")},gK={kernelName:N0,backendName:"webgl",kernelFunc:mK};var jh;(function(n){n.Prod="*",n.Sum="+"})(jh||(jh={}));let fw=class{constructor(e,t,s,r){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];const i=this.outputShape.length,o=this.op===jh.Prod?"1.0":"0.0",a=s?o:`getX(${mw(i,"coords",this.op)})`,l=this.outputShape[this.outputShape.length-1];let c="",u="";s?(c=r?`end != ${l-1}`:"end != 0",u=r?"end + 1":"end - 1"):(c=r?`end + pow2 < ${l}`:"end >= pow2",u=r?"end + pow2":"end - pow2"),this.userCode=` + void main() { + ${an(i)} coords = getOutputCoords(); + int end = ${gw(i,"coords",this.op)}; + float val = ${a}; + int pow2 = int(pow(2.0, index)); + if (${c}) { + int idx = ${u}; + ${gw(i,"coords",this.op)} = idx; + val ${this.op}= getX(${mw(i,"coords",this.op)}); + } + setOutput(val); + } + `}};function mw(n,e,t){if(n===1)return`${e}`;if(n===2)return`${e}.x, ${e}.y`;if(n===3)return`${e}.x, ${e}.y, ${e}.z`;if(n===4)return`${e}.x, ${e}.y, ${e}.z, ${e}.w`;throw new Error(`Cumulative ${t} for rank ${n} is not yet supported`)}function gw(n,e,t){if(n===1)return`${e}`;if(n===2)return`${e}.y`;if(n===3)return`${e}.z`;if(n===4)return`${e}.w`;throw new Error(`Cumulative ${t} for rank ${n} is not yet supported`)}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function YE(n,e,t,s,r,i){const o=e.shape.length,a=ln([s],o);let l=e;a!=null&&(l=Us({inputs:{x:e},backend:t,attrs:{perm:a}}));const c=xn(1,o)[0];if(c!==o-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${e.shape.length-1} but got axis=${s}`);const u=l.shape[c];let h=vr({inputs:{x:l},backend:t});for(let d=0;d<=Math.ceil(Math.log2(u))-1;d++){const p=new fw(n,l.shape,!1,i),f=[[d]],x=h;h=t.runWebGLProgram(p,[h],h.dtype,f),t.disposeIntermediateTensorInfo(x)}if(r){const d=new fw(n,l.shape,r,i),p=h;h=t.runWebGLProgram(d,[h],h.dtype),t.disposeIntermediateTensorInfo(p)}if(a!=null){const d=no(a),p=Us({inputs:{x:h},backend:t,attrs:{perm:d}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(l),p}return h}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xK(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i,exclusive:o,reverse:a}=s;return YE(jh.Prod,r,t,i,o,a)}const vK={kernelName:M0,backendName:"webgl",kernelFunc:xK};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bK(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i,exclusive:o,reverse:a}=s;return YE(jh.Sum,r,t,i,o,a)}const yK={kernelName:pd,backendName:"webgl",kernelFunc:bK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wK(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,weights:i}=e,{size:o,binaryOutput:a}=s;if(r.shape.length===1){const l=t.readSync(r.dataId),c=t.readSync(i.dataId),u=RE(l,c,i.dtype,i.shape,o);return t.makeTensorInfo([o],i.dtype,u)}else if(r.shape.length===2){const l=t.bufferSync(r),c=t.bufferSync(i),u=TG(l,c,o,a);return t.makeTensorInfo(u.shape,i.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}const SK={kernelName:$0,backendName:"webgl",kernelFunc:wK};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let CK=class{constructor(e,t,s){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=s,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int h = ${this.getHeightCoordString()}; + int w = ${this.getWidthCoordString()}; + int d = ${this.getDepthCoordString()}; + + int in_h = h / ${t}; + int offset_h = imod(h, ${t}); + int in_w = w / ${t}; + int offset_w = imod(w, ${t}); + int offset_d = (offset_h * ${t} + offset_w) * + ${this.getOutputDepthSize()}; + int in_d = d + offset_d; + + float result = ${this.getInputSamplingString()}; + setOutput(result); + } + `}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _K(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{blockSize:i,dataFormat:o}=s,a=r.shape[0],l=o==="NHWC"?r.shape[1]:r.shape[2],c=o==="NHWC"?r.shape[2]:r.shape[3],u=o==="NHWC"?r.shape[3]:r.shape[1],h=l*i,d=c*i,p=u/(i*i),f=o==="NHWC"?[a,h,d,p]:[a,p,h,d],x=new CK(f,i,o);return t.runWebGLProgram(x,[r],r.dtype)}const TK={kernelName:D0,backendName:"webgl",kernelFunc:_K};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let ZE=class{constructor(e,t=!1,s=null,r=!1,i=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Ns(this.outputShape.length);const o=e.filterHeight,a=e.filterWidth,l=e.outChannels/e.inChannels;let c="",u="";s&&(r?c=`float activation(float a) { + float b = getPreluActivationWeightsAtOutCoords(); + ${s} + }`:i?c=`float activation(float a) { + float b = getLeakyreluAlphaAtOutCoords(); + ${s} + }`:c=` + float activation(float x) { + ${s} + } + `,u="result = activation(result);");const h=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),i&&this.variableNames.push("leakyreluAlpha"),this.userCode=` + ${c} + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + ivec2 xRCCorner = coords.yz * strides - pads; + int d2 = coords.w; + int d1 = d2 / ${l}; + int q = d2 - d1 * ${l}; + + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations. + for (int wR = 0; wR < ${o}; wR++) { + int xR = xRCorner + wR * dilations[0]; + + if (xR < 0 || xR >= inDims[0]) { + continue; + } + + for (int wC = 0; wC < ${a}; wC++) { + int xC = xCCorner + wC * dilations[1]; + + if (xC < 0 || xC >= inDims[1]) { + continue; + } + + float xVal = getX(batch, xR, xC, d1); + float wVal = getW(wR, wC, d1, q); + dotProd += xVal * wVal; + } + } + + float result = dotProd; + ${h} + ${u} + setOutput(result); + } + `}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class JE{constructor(e,t=!1,s=null,r=!1,i=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Ns(this.outputShape.length);const o=e.outChannels/e.inChannels,a=e.padInfo.left,l=e.strideWidth,c=e.dilationWidth,u=e.filterHeight,h=e.filterWidth,d=h;let p=` + int xR; int xC; int xCOffset; + vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g=0 && xR < inDims[0]) { + `;for(let g=0;g<(d+1)/2;g++){const v=g*2;if(p+=` + xC = xCCorner + ${v*c}; + `,l===1){if(v= 0 && xCOffset < inDims[1] && xTexelC${v}Ready == 0) { + xTexelC${v} = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${v}.zw = vec2(0.0); + } + xTexelC${v}Ready = 1; + } + `,c===1&&v>0?p+=` + xC${v} = vec4(xTexelC${v-2}.zw, xTexelC${v}.xy); + `:p+=` + xCOffset = xC + 1 - 2; + + if (xCOffset >= 0 && xCOffset < inDims[1]) { + previous = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + previous.zw = vec2(0.0); + } + + xC${v} = vec4(previous.zw, xTexelC${v}.xy); + } else { + xC${v} = vec4(0.0, 0.0, xTexelC${v}.xy); + } + `):p+=` + if (xC >= 0 && xC < inDims[1] && xTexelC${v}Ready == 0) { + xTexelC${v} = getX(batch, xR, xC, d1); + if (xC + 1 >= inDims[1]) { + xTexelC${v}.zw = vec2(0.0); + } + xTexelC${v}Ready = 1; + } + + xC${v} = xTexelC${v}; + `,v+1= 0 && xCOffset < inDims[1] && xTexelC${v+1}Ready == 0) { + xTexelC${v+1} = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${v+1}.zw = vec2(0.0); + } + xTexelC${v+1}Ready = 1; + } + `,c>1?p+=` + xCOffset -= 2; + if (xCOffset >= 0 && xCOffset < inDims[1]) { + previous = getX(batch, xR, xCOffset, d1); + xC${v+1} = vec4(previous.zw, xTexelC${v+1}.xy); + } else { + xC${v+1} = vec4(0.0, 0.0, xTexelC${v+1}.xy); + } + `:p+=` + xC${v+1} = vec4(xTexelC${v}.zw, xTexelC${v+1}.xy); + `):b===1?p+=` + xC${v+1} = xTexelC${v}; + `:p+=` + xCOffset = xC + ${b}; + + if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${v+1}Ready == 0) { + xTexelC${v+1} = getX(batch, xR, xCOffset, d1); + if (xCOffset + 1 >= inDims[1]) { + xTexelC${v+1}.zw = vec2(0.0); + } + xTexelC${v+1}Ready = 1; + } + + xC${v+1} = xTexelC${v+1}; + `}}else v= 0 && xCOffset < inDims[1] && xTexelC${v}Ready == 0) { + xTexelC${v} = getX(batch, xR, xCOffset, d1); + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= inDims[1]) { + xTexelC${v}.zw = vec2(0.0); + } + xTexelC${v}Ready = 1; + } + + if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${v+1}Ready == 0) { + xTexelC${v+1} = getX(batch, xR, xC + 1, d1); + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xC + 2 >= inDims[1]) { + xTexelC${v+1}.zw = vec2(0.0); + } + xTexelC${v+1}Ready = 1; + } + + xC${v} = vec4(xTexelC${v}.zw, xTexelC${v+1}.zw); + `,v+1= 0 && xCOffset < inDims[1]) { + final = getX(batch, xR, xCOffset, d1); + } + xC${v+1} = vec4(xTexelC${v+1}.xy, final.xy); + `)):(p+=` + if(xC >= 0 && xC < inDims[1] && xTexelC${v}Ready == 0) { + xTexelC${v} = getX(batch, xR, xC, d1); + if (xC + 1 >= inDims[1]) { + xTexelC${v}.zw = vec2(0.0); + } + xTexelC${v}Ready = 1; + } + + xCOffset = xC + strides[1]; + if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${v+1}Ready == 0) { + xTexelC${v+1} = getX(batch, xR, xCOffset, d1); + if (xCOffset + 1 >= inDims[1]) { + xTexelC${v+1}.zw = vec2(0.); + } + xTexelC${v+1}Ready = 1; + } + + xC${v} = vec4( + xTexelC${v}.xy, xTexelC${v+1}.xy); + `,v+1`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);const h=Cn(r.shape,i.shape,o,u,a,c,!0);let d;oe().getBool("WEBGL_PACK_DEPTHWISECONV")&&h.strideWidth<=2&&h.outChannels/h.inChannels===1?d=new JE(h):d=new ZE(h);const p=[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth]];return t.runWebGLProgram(d,[r,i],"float32",p)}const EK={kernelName:fd,backendName:"webgl",kernelFunc:IK};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let kK=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,s=e.strideWidth,r=e.padInfo.top,i=e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int wR = coords.x; + int wC = coords.y; + int d1 = coords.z; + int dm = coords.w; + int d2 = d1 * ${o} + dm; + + float dotProd = 0.0; + + // TO DO: Vec4 over the batch size + for (int b = 0; b < ${e.batchSize}; b++) { + for (int yR = 0; yR < ${e.outHeight}; yR++) { + int xR = wR + yR * ${t} - ${r}; + + if (xR < 0 || xR >= ${e.inHeight}) { + continue; + } + + for (int yC = 0; yC < ${e.outWidth}; yC++) { + int xC = wC + yC * ${s} - ${i}; + + if (xC < 0 || xC >= ${e.inWidth}) { + continue; + } + + float dyValue = getDy(b, yR, yC, d2); + float xValue = getX(b, xR, xC, d1); + dotProd += (xValue * dyValue); + } + } + } + setOutput(dotProd); + } + `}},AK=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,r=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.top,a=s-1-e.padInfo.left,l=e.outChannels/e.inChannels;this.userCode=` + const ivec2 pads = ivec2(${o}, ${a}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d1 = coords[3]; + ivec2 dyCorner = coords.yz - pads; + int dyRCorner = dyCorner.x; + int dyCCorner = dyCorner.y; + + float dotProd = 0.0; + + for (int wR = 0; wR < ${t}; wR++) { + float dyR = float(dyRCorner + wR) / ${r}.0; + + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = ${t} - 1 - wR; + + for (int wC = 0; wC < ${s}; wC++) { + float dyC = float(dyCCorner + wC) / ${i}.0; + + if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = ${s} - 1 - wC; + + // TO DO: Vec4 over the channelMul + for (int dm = 0; dm < ${l}; dm++) { + int d2 = d1 * ${l} + dm; + float xValue = getDy(batch, idyR, idyC, d2); + float wValue = getW(wRPerm, wCPerm, d1, dm); + dotProd += xValue * wValue; + } + } + } + setOutput(dotProd); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function RK(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,dy:i}=e,{strides:o,dilations:a,pad:l,dimRoundingMode:c,filterShape:u}=s,h=Cn(r.shape,u,o,a,l,c,!0),d=new kK(h);return t.runWebGLProgram(d,[r,i],"float32")}const MK={kernelName:P0,backendName:"webgl",kernelFunc:RK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function NK(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,filter:i}=e,{strides:o,dilations:a,pad:l,dimRoundingMode:c,inputShape:u}=s,h=Cn(u,i.shape,o,a,l,c,!0),d=new AK(h);return t.runWebGLProgram(d,[r,i],"float32")}const $K={kernelName:L0,backendName:"webgl",kernelFunc:NK};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let DK=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0; + setOutput(val); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function PK(n){const{inputs:e,backend:t}=n,{x:s}=e,r=[...s.shape,...s.shape],i=re(s.shape),o=Be({inputs:{x:s},backend:t,attrs:{shape:[i]}}),a=new DK(i),l=t.runWebGLProgram(a,[o],o.dtype),c=Be({inputs:{x:l},backend:t,attrs:{shape:r}});return t.disposeIntermediateTensorInfo(o),t.disposeIntermediateTensorInfo(l),c}const LK={kernelName:h2,backendName:"webgl",kernelFunc:PK};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let FK=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const{inHeight:t,inWidth:s,padInfo:r,strideHeight:i,strideWidth:o,filterHeight:a,filterWidth:l,dilationHeight:c,dilationWidth:u}=e,{top:h,left:d}=r;this.userCode=` + const ivec2 strides = ivec2(${i}, ${o}); + const ivec2 pads = ivec2(${h}, ${d}); + const float neg_infinity = -3.4e38; + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + int d1 = coords.w; + ivec2 outTopLeftCorner = + coords.yz * strides - pads; + int hBeg = outTopLeftCorner.x; + int wBeg = outTopLeftCorner.y; + + float curVal = neg_infinity; + for (int h = 0; h < ${a}; h++) { + int hIn = hBeg + h * ${c}; + + if (hIn >= 0 && hIn < ${t}) { + for (int w = 0; w < ${l}; w++) { + int wIn = wBeg + w * ${u}; + + if (wIn >= 0 && wIn < ${s}) { + float xVal = getX(batch, hIn, wIn, d1); + float wVal = getW(h, w, d1); + + float val = xVal + wVal; + if (val > curVal) { + curVal = val; + } + } + } + } + } + + float result = curVal; + setOutput(result); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function OK(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:i}=e,{strides:o,pad:a,dilations:l}=s,c=Sa(r.shape,i.shape,o,a,"NHWC",l);let u;const h=new FK(c);u=t.runWebGLProgram(h,[r,i],"float32");const d=Be({inputs:{x:u},backend:t,attrs:{shape:c.outShape}});return t.disposeIntermediateTensorInfo(u),d}const zK={kernelName:md,backendName:"webgl",kernelFunc:OK};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function BK(n){const{inputs:e,backend:t,attrs:s}=n,{equation:r}=s,i=e,{allDims:o,summedDims:a,idDims:l}=Rm(r,i.length);Nm(o.length,l,i);const{path:c,steps:u}=$m(a,l),h=u.length;let d=null,p=o.length;const f=[];for(let x=0;x=0&&(d=Zm({inputs:{x:d},backend:t,attrs:{axis:c[x]-(o.length-p),keepDims:!1}}),f.push(d)),p--)}for(const x of f)x!==d&&t.disposeIntermediateTensorInfo(x);return d}const UK={kernelName:F0,backendName:"webgl",kernelFunc:BK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const VK="return (x >= 0.0) ? x : (exp(x) - 1.0);",WK=` + vec4 result; + + result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0); + result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0); + result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0); + result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0); + + return result; +`,GK=Kt({opSnippet:VK,packedOpSnippet:WK}),HK={kernelName:cu,backendName:"webgl",kernelFunc:GK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qK="return (b >= 0.0) ? a : a * (b + 1.0);",XK=` + vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.))); + return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0)))); +`,KK=n=>{const{inputs:e,backend:t}=n,{dy:s,y:r}=e,i=oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new th(XK,s.shape,r.shape):new _l(qK,s.shape,r.shape);return t.runWebGLProgram(i,[s,r],s.dtype)},jK={kernelName:O0,backendName:"webgl",kernelFunc:KK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const YK=` + return vec4(equal(a, b)); +`,ZK="return float(a == b);",JK=_s({opSnippet:ZK,packedOpSnippet:YK,dtype:"bool",cpuKernelImpl:RG}),QK={kernelName:gd,backendName:"webgl",kernelFunc:JK};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ej=` + // Error function is calculated approximately with elementary function. + // See "Handbook of Mathematical Functions with Formulas, + // Graphs, and Mathematical Tables", Abramowitz and Stegun. + float p = ${_m}; + float a1 = ${Tm}; + float a2 = ${Im}; + float a3 = ${Em}; + float a4 = ${km}; + float a5 = ${Am}; + + float sign = sign(x); + x = abs(x); + float t = 1.0 / (1.0 + p * x); + return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x)); +`,tj=Kt({opSnippet:ej}),nj={kernelName:uu,backendName:"webgl",kernelFunc:tj};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const sj=nh+` + return exp(x); +`,rj=` + vec4 result = exp(x); + bvec4 isNaN = isnan(x); + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,QE=Kt({opSnippet:sj,packedOpSnippet:rj,cpuKernelImpl:MG,dtype:"float32"}),ij={kernelName:hu,backendName:"webgl",kernelFunc:QE};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ix(n){const{inputs:e,attrs:t,backend:s}=n,{dim:r}=t,{input:i}=e,o=i.shape.length,a=i.shape.slice();let l=r;return r<0&&(N(-(o+1)<=r,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+r+1),a.splice(l,0,1),Be({inputs:{x:i},backend:s,attrs:{shape:a}})}const oj={kernelName:xd,backendName:"webgl",kernelFunc:Ix};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xw="return exp(x) - 1.0;",aj=Kt({opSnippet:xw,packedOpSnippet:xw,cpuKernelImpl:NG}),lj={kernelName:du,backendName:"webgl",kernelFunc:aj};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let vw=class{constructor(e,t,s){this.variableNames=["real","imag"];const r=t[1];this.outputShape=t;const i=s?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,o=s?`${r}.0`:"1.0";let a;if(e==="real")a="return real * expR - imag * expI;";else if(e==="imag")a="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=` + const float exponentMultiplier = ${i}; + + float unaryOpComplex(float real, float expR, float imag, float expI) { + ${a} + } + + float mulMatDFT(int batch, int index) { + float indexRatio = float(index) / float(${r}); + float exponentMultiplierTimesIndexRatio = + exponentMultiplier * indexRatio; + + float result = 0.0; + + for (int i = 0; i < ${r}; i++) { + // x = (-2|2 * PI / N) * index * i; + float x = exponentMultiplierTimesIndexRatio * float(i); + float expR = cos(x); + float expI = sin(x); + float real = getReal(batch, i); + float imag = getImag(batch, i); + + result += + unaryOpComplex(real, expR, imag, expI) / ${o}; + } + + return result; + } + + void main() { + ivec2 coords = getOutputCoords(); + setOutput(mulMatDFT(coords[0], coords[1])); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ek(n,e,t){const s=t.texData.get(n.dataId),r=re(n.shape),i=n.shape[n.shape.length-1],o=r/i,a=Be({inputs:{x:n},backend:t,attrs:{shape:[o,i]}}),l=a.shape,c=new vw("real",l,e),u=new vw("imag",l,e),h=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:l},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:l}],d=t.runWebGLProgram(c,h,"float32"),p=t.runWebGLProgram(u,h,"float32"),f=ka({inputs:{real:d,imag:p},backend:t});t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(p);const x=Be({inputs:{x:f},backend:t,attrs:{shape:n.shape}});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(f),x}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cj(n){const{inputs:e,backend:t}=n,{input:s}=e;return ek(s,!1,t)}const uj={kernelName:z0,backendName:"webgl",kernelFunc:cj};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let hj=class{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode=` + void main() { + // Input can be obtained from uniform value. + setOutput(value); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yp(n){const{backend:e,attrs:t}=n,{shape:s,value:r}=t;let{dtype:i}=t;if(i=i||Il(r),i==="string"){const o=Pn(i,re(s));return o.fill(r),e.makeTensorInfo(s,i,o)}else{const o=new hj(s,r),a=[[r]];return e.runWebGLProgram(o,[],i,a)}}const dj={kernelName:B0,backendName:"webgl",kernelFunc:yp};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let pj=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int x = coords[2]; + + int coordX = ${t} - x - 1; + float outputValue; + if(coordX >= 0 && coordX < ${t}) { + outputValue = getImage(coords[0], coords[1], coordX, coords[3]); + } else { + outputValue = getImage(coords[0], coords[1], coords[2], coords[3]); + } + setOutput(outputValue); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fj={kernelName:U0,backendName:"webgl",kernelFunc:({inputs:n,backend:e})=>{const{image:t}=n,s=e,r=new pj(t.shape);return s.runWebGLProgram(r,[t],t.dtype)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bw="return floor(x);",mj=Kt({opSnippet:bw,packedOpSnippet:bw,cpuKernelImpl:$G}),gj={kernelName:pu,backendName:"webgl",kernelFunc:mj};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xj=` + float s = sign(a) * sign(b); + int ia = round(a); + int ib = round(b); + if (ib != 0) { + // Windows (D3D) wants guaranteed non-zero int division at compile-time. + return float(idiv(ia, ib, s)); + } else { + return NAN; + } +`,vj=` + ivec4 ia = round(a); + ivec4 ib = round(b); + bvec4 cond = notEqual(ib, ivec4(0)); + ivec4 result = ivec4(0); + vec4 s = sign(a) * sign(b); + + // Windows (D3D) wants guaranteed non-zero int division at compile-time. + if (cond[0]) { + result[0] = idiv(ia[0], ib[0], s[0]); + } + if (cond[1]) { + result[1] = idiv(ia[1], ib[1], s[1]); + } + if (cond[2]) { + result[2] = idiv(ia[2], ib[2], s[2]); + } + if (cond[3]) { + result[3] = idiv(ia[3], ib[3], s[3]); + } + return vec4(result); +`,bj=_s({opSnippet:xj,packedOpSnippet:vj,dtype:"int32"}),yj={kernelName:fu,backendName:"webgl",kernelFunc:bj};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let wj=class{constructor(e){this.variableNames=["A"];const t=Vs(),[s,r]=e;this.outputShape=e,this.userCode=` + void main() { + ivec3 coords = getOutputCoords(); + int texR = coords[0]; + int texC = coords[1]; + int depth = coords[2]; + vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}.0, ${s}.0); + + vec4 values = ${t.texture2D}(A, uv); + float value; + if (depth == 0) { + value = values.r; + } else if (depth == 1) { + value = values.g; + } else if (depth == 2) { + value = values.b; + } else if (depth == 3) { + value = values.a; + } + + setOutput(floor(value * 255.0 + 0.5)); + } + `}};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Sj{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Vs(),[s,r]=e;this.outputShape=e,this.userCode=` + void main() { + ivec3 coords = getOutputCoords(); + int texR = coords[0]; + int texC = coords[1]; + int depth = coords[2]; + + vec4 result = vec4(0.); + + for(int row=0; row<=1; row++) { + for(int col=0; col<=1; col++) { + texC = coords[1] + row; + depth = coords[2] + col; + + vec2 uv = (vec2(texC, texR) + halfCR) / + vec2(${r}.0, ${s}.0); + vec4 values = ${t.texture2D}(A, uv); + float value; + if (depth == 0) { + value = values.r; + } else if (depth == 1) { + value = values.g; + } else if (depth == 2) { + value = values.b; + } else if (depth == 3) { + value = values.a; + } + + result[row * 2 + col] = floor(value * 255.0 + 0.5); + } + } + + ${t.output} = result; + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Cj={kernelName:oC,backendName:"webgl",kernelFunc:_j};let Kl,Wg=oe().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function _j(n){const{inputs:e,backend:t,attrs:s}=n;let{pixels:r}=e;const{numChannels:i}=s,o=typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement,a=typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement,[l,c]=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],u=[c,l],h=[c,l,i];if(a||o){const x=oe().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(Kl==null||x!==Wg)&&(Wg=x,Kl=document.createElement("canvas").getContext("2d",{willReadFrequently:Wg})),Kl.canvas.width=l,Kl.canvas.height=c,Kl.drawImage(r,0,0,l,c),r=Kl.canvas}const d=t.makeTensorInfo(u,"int32");t.texData.get(d.dataId).usage=Er.PIXELS,t.gpgpu.uploadPixelDataToTexture(t.getTexture(d.dataId),r);const p=oe().getBool("WEBGL_PACK")?new Sj(h):new wj(h),f=t.runWebGLProgram(p,[d],"int32");return t.disposeData(d.dataId),f}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Tj(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:i,bias:o,preluActivationWeights:a}=e,{strides:l,pad:c,dataFormat:u,dilations:h,dimRoundingMode:d,activation:p,leakyreluAlpha:f}=s,x=wr(u),m=Cn(r.shape,i.shape,l,h,c,d,!1,x);let g;const v=[],b=o!=null,y=a!=null,w=p==="leakyrelu",C=()=>{const E=[r,i],R=(_,k)=>{if(k==="NCHW"&&_.shape.length===1&&_.shape[0]!==1){const F=Be({inputs:{x:_},backend:t,attrs:{shape:[_.shape[0],1,1]}});return v.push(F),F}return _};if(b&&E.push(R(o,u)),y&&E.push(R(a,u)),w){const _=t.makeTensorInfo([],"float32",ya(f,"float32"));E.push(_),v.push(_)}return E};if(m.filterHeight===1&&m.filterWidth===1&&m.dilationHeight===1&&m.dilationWidth===1&&m.strideHeight===1&&m.strideWidth===1&&(m.padInfo.type==="SAME"||m.padInfo.type==="VALID"))g=KE({x:r,filter:i,convInfo:m,backend:t,bias:o,activation:p,preluActivationWeights:a,leakyreluAlpha:f});else if(m.strideWidth<=2&&x==="channelsLast"&&oe().getBool("WEBGL_EXP_CONV")){const E=p?Xh(p,!0):null,R=new XE(m,b,E,y,w),_=[[m.padInfo.top,m.padInfo.left],[m.strideHeight,m.strideWidth],[m.dilationHeight,m.dilationWidth],[m.inHeight,m.inWidth]],k=C();g=t.runWebGLProgram(R,k,"float32",_)}else if(oe().getBool("WEBGL_CONV_IM2COL"))g=jE({x:r,filter:i,convInfo:m,backend:t,bias:o,activation:p,preluActivationWeights:a,leakyreluAlpha:f});else{const E=p?Xh(p,!1):null,R=new qE(m,b,E,y,w),_=C();g=t.runWebGLProgram(R,_,"float32")}const T=Be({inputs:{x:g},backend:t,attrs:{shape:m.outShape}});return v.push(g),v.forEach(E=>t.disposeIntermediateTensorInfo(E)),T}const Ij={kernelName:Lh,backendName:"webgl",kernelFunc:Tj};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ej(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:i,bias:o,preluActivationWeights:a}=e,{strides:l,pad:c,dilations:u,dimRoundingMode:h,activation:d,leakyreluAlpha:p}=s,f=[];let x=u;x==null&&(x=[1,1]),N(gs(l,x),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${x}'`);const m=Cn(r.shape,i.shape,l,x,c,h,!0),g=oe().getBool("WEBGL_PACK_DEPTHWISECONV")&&m.strideWidth<=2&&m.outChannels/m.inChannels===1,v=d?Xh(d,g):null,b=[r,i],y=o!=null,w=a!=null,C=d==="leakyrelu";if(y&&b.push(o),w&&b.push(a),C){const _=t.makeTensorInfo([],"float32",ya(p,"float32"));b.push(_),f.push(_)}let T;g?T=new JE(m,y,v,w,C):T=new ZE(m,y,v,w,C);const E=[[m.padInfo.top,m.padInfo.left],[m.strideHeight,m.strideWidth],[m.dilationHeight,m.dilationWidth],[m.inHeight,m.inWidth]],R=t.runWebGLProgram(T,b,"float32",E);return f.forEach(_=>t.disposeIntermediateTensorInfo(_)),R}const kj={kernelName:I2,backendName:"webgl",kernelFunc:Ej};let Aj=class{constructor(e,t,s,r){this.sliceDim=e,this.strides=t,this.paramsShape=r,this.variableNames=["x","indices"],this.outputShape=s;const i=an(s.length);let o=` + int index;`;for(let a=0;a= ${this.paramsShape[a]}; + flattenIndex += index * ${this.strides[a]};`;this.userCode=` + void main() { + ${i} coords = getOutputCoords(); + int flattenIndex = 0; + bool out_of_bounds = false; + + ${o} + + setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1])); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Rj(n){const{inputs:e,backend:t}=n,{params:s,indices:r}=e,i=r.shape,o=i[i.length-1],a=re(s.shape),[l,c,u,h]=xm(s,r),d=Be({inputs:{x:r},backend:t,attrs:{shape:[c,o]}}),p=Be({inputs:{x:s},backend:t,attrs:{shape:[re(s.shape)/u,u]}});if(t.shouldExecuteOnCPU([s,r])||s.dtype==="string"){const g=t.readSync(r.dataId),v=t.bufferSync(s),b=DG(g,v,s.dtype,c,o,u,h,s.shape,a);return t.makeTensorInfo(l,s.dtype,b.values)}const f=new Aj(o,h,[c,u],s.shape),x=t.runWebGLProgram(f,[p,d],p.dtype),m=Be({inputs:{x},backend:t,attrs:{shape:l}});return t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(x),m}const Mj={kernelName:d2,backendName:"webgl",kernelFunc:Rj};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Nj=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const s=an(this.rank),r=$j(e);this.userCode=` + void main() { + ${s} resRC = getOutputCoords(); + int index = int(getIndices(resRC.x, resRC.z)); + float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0; + setOutput(inBounds * getA(${r})); + } + `}};function $j(n,e){const t=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let r=0;r=0,()=>`GatherV2: the index value ${w} is not in [0, ${b-1}]`)}}const c=gv(r,i,l,a),u=re(i.shape),h=[],d=Be({inputs:{x:r},backend:t,attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]}}),p=Be({inputs:{x:i},backend:t,attrs:{shape:[c.batchSize,u/c.batchSize]}});h.push(d),h.push(p);const f=[c.batchSize,c.outerSize,u/c.batchSize,c.sliceSize];if(t.shouldExecuteOnCPU([r,i])||r.dtype==="string"){const v=t.bufferSync(p),b=t.bufferSync(d),y=PG(b,v,f);return h.forEach(w=>t.disposeIntermediateTensorInfo(w)),t.makeTensorInfo(c.outputShape,y.dtype,y.values)}const x=new Nj(d.shape,f),m=t.runWebGLProgram(x,[d,p],d.dtype);h.push(m);const g=Be({inputs:{x:m},backend:t,attrs:{shape:c.outputShape}});return h.forEach(v=>t.disposeIntermediateTensorInfo(v)),g}const Dj={kernelName:bd,backendName:"webgl",kernelFunc:tk};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Pj="return float(a > b);",Lj=` + return vec4(greaterThan(a, b)); +`,Fj=_s({opSnippet:Pj,packedOpSnippet:Lj,cpuKernelImpl:LG,dtype:"bool"}),Oj={kernelName:yd,backendName:"webgl",kernelFunc:Fj};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const zj="return float(a >= b);",Bj=` + return vec4(greaterThanEqual(a, b)); +`,Uj=_s({opSnippet:zj,packedOpSnippet:Bj,dtype:"bool",cpuKernelImpl:FG}),Vj={kernelName:mu,backendName:"webgl",kernelFunc:Uj};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Wj(n){const{inputs:e,backend:t}=n,{input:s}=e;return ek(s,!0,t)}const Gj={kernelName:V0,backendName:"webgl",kernelFunc:Wj};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Hj="return float(!isnan(x) && !isinf(x));",qj=Kt({opSnippet:Hj,dtype:"bool"}),Xj={kernelName:xu,backendName:"webgl",kernelFunc:qj};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Kj="return float(isinf(x));",jj=Kt({opSnippet:Kj,dtype:"bool"}),Yj={kernelName:vu,backendName:"webgl",kernelFunc:jj};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Zj="return float(isnan(x));",Jj=Kt({opSnippet:Zj,dtype:"bool"}),Qj={kernelName:bu,backendName:"webgl",kernelFunc:Jj};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eY="return float(a < b);",tY=` + return vec4(lessThan(a, b)); +`,nY=_s({opSnippet:eY,packedOpSnippet:tY,cpuKernelImpl:OG,dtype:"bool"}),sY={kernelName:Sd,backendName:"webgl",kernelFunc:nY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rY="return float(a <= b);",iY=` + return vec4(lessThanEqual(a, b)); +`,oY=_s({opSnippet:rY,packedOpSnippet:iY,cpuKernelImpl:zG,dtype:"bool"}),aY={kernelName:Cd,backendName:"webgl",kernelFunc:oY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function lY(n){const{backend:e,attrs:t}=n,{start:s,stop:r,num:i}=t,o=BG(s,r,i);return e.makeTensorInfo([o.length],"float32",o)}const cY={kernelName:p2,backendName:"webgl",kernelFunc:lY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uY=nh+` + return x < 0.0 ? 0./0. : log(x); +`,hY=` + vec4 result = log(x); + bvec4 isNaN = isnan(x); + result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r); + result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g); + result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b); + result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a); + return result; +`,dY=Kt({opSnippet:uY,packedOpSnippet:hY,cpuKernelImpl:UG}),pY={kernelName:yu,backendName:"webgl",kernelFunc:dY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fY=nh+` + return log(1.0 + x); +`,mY=Kt({opSnippet:fY}),gY={kernelName:wu,backendName:"webgl",kernelFunc:mY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xY="return float(a >= 1.0 && b >= 1.0);",vY=` + return vec4( + vec4(greaterThanEqual(a, vec4(1.0))) * + vec4(greaterThanEqual(b, vec4(1.0)))); +`,bY=_s({opSnippet:xY,packedOpSnippet:vY,dtype:"bool"}),yY={kernelName:_d,backendName:"webgl",kernelFunc:bY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wY="return float(!(x >= 1.0));",SY=Kt({opSnippet:wY}),CY={kernelName:Td,backendName:"webgl",kernelFunc:SY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _Y="return float(a >= 1.0 || b >= 1.0);",TY=` + return min( + vec4(greaterThanEqual(a, vec4(1.0))) + + vec4(greaterThanEqual(b, vec4(1.0))), + vec4(1.0)); +`,IY=_s({opSnippet:_Y,packedOpSnippet:TY,dtype:"bool"}),EY={kernelName:Id,backendName:"webgl",kernelFunc:IY};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let kY=class{constructor(e,t,s,r,i){this.variableNames=["x"],this.outputShape=[];const o=t,a=e[3]-1;this.outputShape=e;let l;const c=`float(${s}) + float(${r}) * sum`;i===.5?l=`inversesqrt(${c})`:i===1?l=`1.0/(${c})`:l=`exp(log(${c}) * float(-${i}));`,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int r = coords[1]; + int c = coords[2]; + int d = coords[3]; + float x = getX(b, r, c, d); + float sum = 0.0; + for (int j = -${o}; j <= ${o}; j++) { + int idx = d + j; + if (idx >= 0 && idx <= ${a}) { + float z = getX(b, r, c, idx); + sum += z * z; + } + } + float val = x * ${l}; + setOutput(val); + } + `}};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class AY{constructor(e,t,s,r,i){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const o=t,a=e[3]-1;this.outputShape=e;let l;const c=`float(${s}) + float(${r}) * sum`;i===.5?l=`inversesqrt(${c})`:i===1?l=`1.0/(${c})`:l=`exp(log(${c}) * float(-${i}));`,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords.x; + int r = coords.y; + int c = coords.z; + int d = coords.w; + + bool hasNextCol = d < ${this.outputShape[3]}; + bool hasNextRow = c < ${this.outputShape[2]}; + + vec4 sum = vec4(0.); + vec4 xFragAtOutputCoords = getX(b, r, c, d); + + vec4 xAtOutputCoords = vec4( + getChannel(xFragAtOutputCoords, vec2(c, d)), + hasNextCol ? + getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0, + hasNextRow ? + getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0, + (hasNextRow && hasNextCol) ? + getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0 + ); + + int firstChannel = d - ${o}; + vec2 cache = vec2(0.); + if(firstChannel >= 0){ + vec4 firstChannelFrag = getX(b, r, c, firstChannel); + cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel)); + if(hasNextRow){ + cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel)); + } + } + + ivec2 depth = ivec2(d, d + 1); + for (int j = - ${o}; j <= ${o}; j++) { + ivec2 idx = depth + j; + bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0)); + bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${a})); + + bool depthInRange = aboveLowerBound.x && belowUpperBound.x; + bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y; + + if(depthInRange || depthPlusOneInRange){ + vec4 z = vec4(0.); + vec4 xFragAtCurrentDepth; + z.xz = cache.xy; + if(depthPlusOneInRange && hasNextCol){ + xFragAtCurrentDepth = idx.y != d ? + getX(b, r, c, idx.y) : xFragAtOutputCoords; + z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y)); + if(hasNextRow){ + z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y)); + } + } + cache.xy = z.yw; + sum += z * z; + } + } + vec4 result = xAtOutputCoords * ${l}; + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const RY=n=>{const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{depthRadius:i,bias:o,alpha:a,beta:l}=s,c=oe().getBool("WEBGL_PACK_NORMALIZATION")?new AY(r.shape,i,o,a,l):new kY(r.shape,i,o,a,l);return t.runWebGLProgram(c,[r],r.dtype)},MY={kernelName:Ed,backendName:"webgl",kernelFunc:RY};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let NY=class{constructor(e,t,s,r,i){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=s,this.alpha=r,this.beta=i,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int r = coords[1]; + int c = coords[2]; + + float result = 0.0; + for (int d = 0; d < ${this.depth}; ++d) { + int depthBegin = int(max(0.0, float(d - ${t}))); + int depthEnd = int(min(float(${this.depth}), + float(d + ${t} + 1))); + + const int MIN_DEPTH_BEGIN = 0; + const int MAX_DEPTH_END = ${this.depth}; + + float norm = 0.0; + for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) { + if (k < depthBegin){ + continue; + } + else if (k >= depthBegin && k < depthEnd) { + norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k); + } + else { + break; + } + } + + norm = float(${r}) * norm + float(${s}); + + for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){ + if (k < depthBegin){ + continue; + } + else if (k >= depthBegin && k < depthEnd){ + float dyi = -2.0 * float(${r}) + * float(${i}) + * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d) + / norm; + if (k == d) { + dyi += pow(norm, -1.0 * ${i}); + } + if (k == coords[3]) { + dyi *= getDy(b, r, c, d); + result += dyi; + } + } + else { + break; + } + } + } + setOutput(result); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $Y=n=>{const{inputs:e,backend:t,attrs:s}=n,{x:r,y:i,dy:o}=e,{depthRadius:a,bias:l,alpha:c,beta:u}=s,h=new NY(r.shape,a,l,c,u);return t.runWebGLProgram(h,[r,i,o],r.dtype)},DY={kernelName:G0,backendName:"webgl",kernelFunc:$Y};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function PY(n,e,t,s){const r=re(e),o=re(n.shape)/r,a=Be({inputs:{x:n},attrs:{shape:[o,r]},backend:s}),l=Vl(a,n.dtype,"max",s),c=Be({inputs:{x:l},attrs:{shape:t},backend:s});return s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(l),c}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nk(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{reductionIndices:i,keepDims:o}=s,a=r.shape.length,l=It(i,r.shape);let c=l;const u=ln(c,a),h=u!=null,d=t.shouldExecuteOnCPU([r]);let p=r;if(h){if(d){const b=t.texData.get(p.dataId).values,y=new Array(a);for(let T=0;T`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const u=Rs(r.shape,i,o,c,a,l);if(u.filterWidth===1&&u.filterHeight===1&&Wt(u.inShape,u.outShape))return vr({inputs:{x:r},backend:t});const h=new Kh(u,"max",!1);return t.runWebGLProgram(h,[r],r.dtype)}const VY={kernelName:Ad,backendName:"webgl",kernelFunc:UY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function WY(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{filterSize:i,strides:o,pad:a,dataFormat:l,dimRoundingMode:c}=s,u=[1,1,1],h=$r(r.shape,i,o,u,a,c,l),d=new tb(h,"max",!1);return t.runWebGLProgram(d,[r],r.dtype)}const GY={kernelName:Rd,backendName:"webgl",kernelFunc:WY};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let HY=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,s=e.strideWidth,r=e.dilationHeight,i=e.effectiveFilterHeight,o=e.effectiveFilterWidth,a=i-1-e.padInfo.top,l=o-1-e.padInfo.left,c=i*o-1;this.userCode=` + const ivec2 pads = ivec2(${a}, ${l}); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + + ivec2 dyRCCorner = coords.yz - pads; + int dyRCorner = dyRCCorner.x; + int dyCCorner = dyRCCorner.y; + + // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${i}; + wR += ${r}) { + float dyR = float(dyRCorner + wR) / ${t}.0; + + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${o}; wC++) { + float dyC = float(dyCCorner + wC) / ${s}.0; + + if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(b, idyR, idyC, d); + int maxPosValue = ${c} - int(getMaxPos(b, idyR, idyC, d)); + + // Get the current value, check it against the value from the + // position matrix. + int curPosValue = wR * ${o} + wC; + float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); + + dotProd += dyValue * mask; + } + } + setOutput(dotProd); + } + `}},qY=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,s=e.strideHeight,r=e.strideWidth,i=e.dilationDepth,o=e.dilationHeight,a=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,u=e.effectiveFilterWidth,h=l-1-e.padInfo.front,d=c-1-e.padInfo.top,p=u-1-e.padInfo.left,f=l*c*u-1;this.userCode=` + const ivec3 pads = ivec3(${h}, ${d}, ${p}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; + int dyDCorner = dyCorner.x; + int dyRCorner = dyCorner.y; + int dyCCorner = dyCorner.z; + + // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get + // dx(xD, xR, xC, ch). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + + for (int wD = 0; wD < ${l}; + wD += ${i}) { + float dyD = float(dyDCorner + wD) / ${t}.0; + + if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) { + continue; + } + int idyD = int(dyD); + + for (int wR = 0; wR < ${c}; + wR += ${o}) { + float dyR = float(dyRCorner + wR) / ${s}.0; + + if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${u}; + wC += ${a}) { + float dyC = float(dyCCorner + wC) / ${r}.0; + + if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(batch, idyD, idyR, idyC, ch); + int maxPosValue = ${f} - + int(getMaxPos(batch, idyD, idyR, idyC, ch)); + + // Get the current value, check it against the value from the + // position matrix. + int curPosValue = + wD * ${c} * ${u} + + wR * ${u} + wC; + float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); + + dotProd += dyValue * mask; + } + } + } + setOutput(dotProd); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function XY(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:i}=e,o=i,{filterSize:a,strides:l,pad:c,dimRoundingMode:u}=s,h=[1,1,1],d=$r(o.shape,a,l,h,c,u),p=new tb(d,"max",!0),f=t.runWebGLProgram(p,[o],o.dtype),x=new qY(d),m=t.runWebGLProgram(x,[r,f],o.dtype);return t.disposeIntermediateTensorInfo(f),m}const KY={kernelName:q0,backendName:"webgl",kernelFunc:XY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jY(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:i,output:o}=e,a=i;xp([i,o],"maxPoolGrad");const{filterSize:l,strides:c,pad:u,dimRoundingMode:h}=s,d=Rs(a.shape,l,c,1,u,h),p=!0,f=new Kh(d,"max",p),x=t.runWebGLProgram(f,[a],a.dtype),m=new HY(d),g=t.runWebGLProgram(m,[r,x],a.dtype);return t.disposeIntermediateTensorInfo(x),g}const YY={kernelName:H0,backendName:"webgl",kernelFunc:jY};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ZY(n,e,t,s){let r=new Kh(t,"max",!1);const i=s.runWebGLProgram(r,[n],"float32");r=new Kh(t,"max",!0,!0,e);const o=s.runWebGLProgram(r,[n],"float32");return[i,o]}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const JY={kernelName:f2,backendName:"webgl",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{x:s}=n,{filterSize:r,strides:i,pad:o,includeBatchInIndex:a}=e,l=t;N(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);const c=[1,1];N(gs(i,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);const u=Rs(s.shape,r,i,c,o),[h,d]=ZY(s,a,u,l);return[h,d]}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function QY(n,e,t,s){const r=re(e),o=re(n.shape)/r,a=Be({inputs:{x:n},attrs:{shape:[o,r]},backend:s}),l=Vl(a,"float32","mean",s),c=Be({inputs:{x:l},attrs:{shape:t},backend:s});return s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(l),c}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eZ={kernelName:Md,backendName:"webgl",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{x:s}=n,{keepDims:r,axis:i}=e,o=t,a=s.shape.length,l=It(i,s.shape);let c=l;const u=ln(c,a),h=u!=null,d=o.shouldExecuteOnCPU([s]),p=[];let f=s;if(h){if(d){const y=o.texData.get(f.dataId).values,w=new Array(a);for(let E=0;Eu[0]+e[h]+u[1]);const r=e.length,i=an(r),o=t.map(u=>u[0]).join(","),a=t.map((u,h)=>u[0]+e[h]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),c=s==="reflect"?0:1;if(r===1){this.userCode=` + int start = ${o}; + int end = ${a}; + + void main() { + int outC = getOutputCoords(); + if (outC < start) { + outC = start * 2 - outC - ${c}; + } else if(outC >= end) { + outC = (end - 1) * 2 - outC + ${c}; + } + setOutput(getX(outC - start)); + } + `;return}this.userCode=` + ${i} start = ${i}(${o}); + ${i} end = ${i}(${a}); + + void main() { + ${i} outC = getOutputCoords(); + for (int i = 0; i < ${r}; i++) { + if (outC[i] < start[i]) { + outC[i] = start[i] * 2 - outC[i] - ${c}; + } else if(outC[i] >= end[i]) { + outC[i] = (end[i] - 1) * 2 - outC[i] + ${c}; + } + } + ${i} coords = outC - start; + setOutput(getX(${l})); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class lZ{constructor(e,t,s){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((f,x)=>f[0]+e[x]+f[1]);const r=e.length,i=an(r),o=t.map(f=>f[0]).join(","),a=t.map((f,x)=>f[0]+e[x]).join(","),l=Os("rc",r),c=Os("source",r),u=`${l[r-1]} < ${this.outputShape[r-1]}`,h=r===1?"source":`vec2(${c.slice(-2).join()})`,d=s==="reflect"?0:1;let p="";if(r===1){const f=` + ${i} source = rc; + if (source < start) { + source = start * 2 - source - ${d}; + } else if (source >= end) { + source = (end - 1) * 2 - source + ${d}; + } + source -= start; + `;p=` + ${i} rc = outputLoc; + ${f} + result[0] = getChannel(getX(${c.join()}), ${h}); + ${l[r-1]} += 1; + if(${u}) { + ${f} + result[1] = getChannel(getX(${c.join()}), ${h}); + } + `}else{const f=` + ${i} source = rc; + ${i} lt = ${i}(lessThan(source, start)); + ${i} gte = ${i}(greaterThanEqual(source, end)); + ${i} orig = 1 - (lt + gte); + source = orig * source + + lt * (start * 2 - source - ${d}) + + gte * ((end - 1) * 2 - source + ${d}); + source -= start; + `;p=` + ${i} rc = outputLoc; + ${f} + result[0] = getChannel(getX(${c.join()}), ${h}); + ${l[r-1]} += 1; + if(${u}) { + ${f} + result[1] = getChannel(getX(${c.join()}), ${h}); + } + rc = outputLoc; + ${l[r-2]} += 1; + if(${l[r-2]} < ${this.outputShape[r-2]}) { + ${f} + result[2] = getChannel(getX(${c.join()}), ${h}); + ${l[r-1]} += 1; + if(${u}) { + ${f} + result[3] = getChannel(getX(${c.join()}), ${h}); + } + } + `}this.userCode=` + const ${i} start = ${i}(${o}); + const ${i} end = ${i}(${a}); + + void main() { + ${i} outputLoc = getOutputCoords(); + vec4 result = vec4(0.); + ${p} + setOutput(result); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cZ=({inputs:n,backend:e,attrs:t})=>{const{x:s}=n,{paddings:r,mode:i}=t,o=oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new lZ(s.shape,r,i):new aZ(s.shape,r,i);return e.runWebGLProgram(o,[s],s.dtype)},uZ={kernelName:$d,backendName:"webgl",kernelFunc:cZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hZ=`if (b == 0.0) return NAN; + return mod(a, b);`,dZ=` + vec4 result = mod(a, b); + bvec4 isNaN = equal(b, vec4(0.0)); + `+Ul+` + return result; +`,pZ=_s({opSnippet:hZ,packedOpSnippet:dZ}),fZ={kernelName:_u,backendName:"webgl",kernelFunc:pZ};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let mZ=class{constructor(e,t,s){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,s],this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + + float r = random(seed); + float cdf = 0.0; + + for (int i = 0; i < ${t-1}; i++) { + cdf += getProbs(batch, i); + + if (r < cdf) { + setOutput(float(i)); + return; + } + } + + // If no other event happened, last event happened. + setOutput(float(${t-1})); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gZ=` +if (a == b) { + return 1.0; +}; +return a / b;`,xZ=` + // vec4 one = vec4(equal(a, b)); + // return one + (vec4(1.0) - one) * a / b; + vec4 result = a / b; + if(a.x == b.x) { + result.x = 1.; + } + if(a.y == b.y) { + result.y = 1.; + } + if(a.z == b.z) { + result.z = 1.; + } + if(a.w == b.w) { + result.w = 1.; + } + + return result; +`,sk=_s({opSnippet:gZ,packedOpSnippet:xZ,checkOutOfBounds:!0}),vZ={kernelName:lu,backendName:"webgl",kernelFunc:sk};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yw="return a - b;",rk=_s({opSnippet:yw,packedOpSnippet:yw,supportsComplex:!0,cpuKernelImpl:hH}),bZ={kernelName:Bu,backendName:"webgl",kernelFunc:rk};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ik(n){const{inputs:e,backend:t,attrs:s}=n,{logits:r}=e,{dim:i}=s,o=It([i],r.shape),a=nk({inputs:{x:r},backend:t,attrs:{reductionIndices:o,keepDims:!1}}),l=Vn(a.shape,o),c=Be({inputs:{x:a},backend:t,attrs:{shape:l}}),u=rk({inputs:{a:r,b:c},backend:t}),h=QE({inputs:{x:u},backend:t}),d=Zm({inputs:{x:h},backend:t,attrs:{axis:o,keepDims:!1}}),p=Be({inputs:{x:d},backend:t,attrs:{shape:l}}),f=sk({inputs:{a:h,b:p},backend:t});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(p),f}const yZ={kernelName:Zd,backendName:"webgl",kernelFunc:ik};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wZ(n){const{inputs:e,backend:t,attrs:s}=n,{logits:r}=e,{numSamples:i,seed:o,normalized:a}=s,l=a?r:ik({inputs:{logits:r},backend:t,attrs:{dim:r.shape.length-1}}),c=l.shape[0],u=l.shape[1],h=new mZ(c,u,i),d=[[o]],p=t.runWebGLProgram(h,[l],"int32",d);return a||t.disposeIntermediateTensorInfo(l),p}const SZ={kernelName:m2,backendName:"webgl",kernelFunc:wZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const CZ=ri+` + return -x; +`,_Z=` + vec4 result = -x; + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`;function TZ(n){const{inputs:e,backend:t}=n,{x:s}=e;if(t.shouldExecuteOnCPU([s])){const i=t.texData.get(s.dataId),[o,a]=qG(i.values,s.shape,s.dtype);return t.makeTensorInfo(a,s.dtype,o)}let r;return oe().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Yo(s.shape,_Z):r=new Vi(s.shape,CZ),t.runWebGLProgram(r,[s],s.dtype)}const IZ={kernelName:Dd,backendName:"webgl",kernelFunc:TZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const EZ=mm;function kZ(n){Ir("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:e,backend:t,attrs:s}=n,{boxes:r,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:l}=s,c=t.readSync(r.dataId),u=t.readSync(i.dataId),{selectedIndices:h}=EZ(c,u,o,a,l);return t.makeTensorInfo([h.length],"int32",new Int32Array(h))}const AZ={kernelName:X0,backendName:"webgl",kernelFunc:kZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const RZ=av;function MZ(n){Ir("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:e,backend:t,attrs:s}=n,{boxes:r,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:l,padToMaxOutputSize:c}=s,u=t.readSync(r.dataId),h=t.readSync(i.dataId),{selectedIndices:d,validOutputs:p}=RZ(u,h,o,a,l,c);return[t.makeTensorInfo([d.length],"int32",new Int32Array(d)),t.makeTensorInfo([],"int32",new Int32Array([p]))]}const NZ={kernelName:g2,backendName:"webgl",kernelFunc:MZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $Z=gm;function DZ(n){Ir("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:e,backend:t,attrs:s}=n,{boxes:r,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:l,softNmsSigma:c}=s,u=t.readSync(r.dataId),h=t.readSync(i.dataId),d=o,p=a,f=l,x=c,{selectedIndices:m,selectedScores:g}=$Z(u,h,d,p,f,x);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([g.length],"float32",new Float32Array(g))]}const PZ={kernelName:K0,backendName:"webgl",kernelFunc:DZ};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let LZ=class{constructor(e,t,s,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int index = round(getIndices(coords.x)); + setOutput(mix(float(${r}), float(${s}), + float(index == coords.y))); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const FZ=n=>{const{inputs:e,backend:t,attrs:s}=n,{indices:r}=e,{dtype:i,depth:o,onValue:a,offValue:l}=s,c=re(r.shape),u=new LZ(c,o,a,l),h=Be({inputs:{x:r},backend:t,attrs:{shape:[c]}}),d=t.runWebGLProgram(u,[h],i);t.disposeIntermediateTensorInfo(h);const p=[...r.shape,o],f=Be({inputs:{x:d},backend:t,attrs:{shape:p}});return t.disposeIntermediateTensorInfo(d),f},OZ={kernelName:Fd,backendName:"webgl",kernelFunc:FZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function s0(n){const{inputs:e,backend:t}=n,{x:s}=e;if(s.dtype==="complex64"){const r=bp({inputs:{input:s},backend:t}),i=s0({inputs:{x:r},backend:t}),o=Jm({inputs:{input:s},backend:t}),a=s0({inputs:{x:o},backend:t}),l=ka({inputs:{real:i,imag:a},backend:t});return t.disposeIntermediateTensorInfo(r),t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(o),t.disposeIntermediateTensorInfo(a),l}else return yp({attrs:{shape:s.shape,dtype:s.dtype,value:s.dtype==="string"?"":0},backend:t})}const zZ={kernelName:ep,backendName:"webgl",kernelFunc:s0};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ok(n){const{inputs:e,backend:t}=n,{x:s}=e;if(s.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(s.dtype==="complex64"){const r=bp({inputs:{input:s},backend:t}),i=ok({inputs:{x:r},backend:t}),o=Jm({inputs:{input:s},backend:t}),a=s0({inputs:{x:o},backend:t}),l=ka({inputs:{real:i,imag:a},backend:t});return t.disposeIntermediateTensorInfo(r),t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(o),t.disposeIntermediateTensorInfo(a),l}else return yp({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:t})}const BZ={kernelName:Ld,backendName:"webgl",kernelFunc:ok};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function UZ(n){const{inputs:e,backend:t,attrs:s}=n,{axis:r}=s;if(e.length===1)return Ix({inputs:{input:e[0]},backend:t,attrs:{dim:r}});const i=e[0].shape,o=e[0].dtype;e.forEach(u=>{y0(i,u.shape,"All tensors passed to stack must have matching shapes"),N(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=[],l=e.map(u=>{const h=Ix({inputs:{input:u},backend:t,attrs:{dim:r}});return a.push(h),h}),c=HE({inputs:l,backend:t,attrs:{axis:r}});return a.forEach(u=>t.disposeIntermediateTensorInfo(u)),c}const VZ={kernelName:Od,backendName:"webgl",kernelFunc:UZ};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let WZ=class{constructor(e,t,s){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((c,u)=>c[0]+e[u]+c[1]);const r=e.length,i=an(r),o=t.map(c=>c[0]).join(","),a=t.map((c,u)=>c[0]+e[u]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);if(r===1){this.userCode=` + int start = ${o}; + int end = ${a}; + + void main() { + int outC = getOutputCoords(); + if (outC < start || outC >= end) { + setOutput(value); + } else { + setOutput(getX(outC - start)); + } + } + `;return}this.userCode=` + ${i} start = ${i}(${o}); + ${i} end = ${i}(${a}); + + void main() { + ${i} outC = getOutputCoords(); + if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) { + setOutput(value); + } else { + ${i} coords = outC - start; + setOutput(getX(${l})); + } + } + `}};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class GZ{constructor(e,t,s){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((x,m)=>x[0]+e[m]+x[1]);const r=e.length,i=an(r),o=t.map(x=>x[0]).join(","),a=t.map((x,m)=>x[0]+e[m]).join(","),l=Os("rc",r),c=Os("source",r),u=`${l[r-1]} < ${this.outputShape[r-1]}`,h=r===1?"source":`vec2(${c.slice(-2).join()})`,d=[`${i} rc = outputLoc;`,`${l[r-1]} += 1; + if(${u}) { + `,r===1?"":`} + rc = outputLoc; + ${l[r-2]} += 1; + if(${l[r-2]} < ${this.outputShape[r-2]}) {`,r===1?"":` ${l[r-1]} += 1; + if(${u}) {`],p=r===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let f="";for(let x=0,m=r===1?2:4;x{const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{paddings:i,constantValue:o}=s;if(re(r.shape)===0){const c=i.map((u,h)=>u[0]+r.shape[h]+u[1]);return yp({backend:t,attrs:{shape:c,value:o,dtype:r.dtype}})}const a=oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new GZ(r.shape,i,o):new WZ(r.shape,i,o),l=[[o]];return t.runWebGLProgram(a,[r],r.dtype,l)},HZ={kernelName:zd,backendName:"webgl",kernelFunc:ak};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qZ=` + if(a < 0.0 && floor(b) < b){ + return NAN; + } + if (b == 0.0) { + return 1.0; + } + return (round(mod(b, 2.0)) != 1) ? + pow(abs(a), b) : sign(a) * pow(abs(a), b); +`,XZ=` + // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise. + vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1))); + vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1); + vec4 result = multiplier * pow(abs(a), b); + + // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS + bvec4 isExpZero = equal(b, vec4(0.0)); + result.r = isExpZero.r ? 1.0 : result.r; + result.g = isExpZero.g ? 1.0 : result.g; + result.b = isExpZero.b ? 1.0 : result.b; + result.a = isExpZero.a ? 1.0 : result.a; + + bvec4 isNaN1 = lessThan(a, vec4(0.0)); + bvec4 isNaN2 = lessThan(floor(b), b); + bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w); + `+Ul+` + return result; +`,KZ=_s({opSnippet:qZ,packedOpSnippet:XZ}),jZ={kernelName:Iu,backendName:"webgl",kernelFunc:KZ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function YZ(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i,keepDims:o}=s,a=r.shape.length,l=[],c=It(i,r.shape);let u=c;const h=ln(u,a);let d=r;h!=null&&(d=Us({inputs:{x:r},backend:t,attrs:{perm:h}}),u=xn(u.length,a),l.push(d)),Kn("prod",u,a);let p;if(t.shouldExecuteOnCPU([d])){const f=t.texData.get(d.dataId).values,{outVals:x,outShape:m,outDtype:g}=KG(d.shape,d.dtype,f,u);p=t.makeTensorInfo(m,g,x)}else{const[f,x]=Wn(d.shape,u),m=re(x),g=Be({inputs:{x:d},backend:t,attrs:{shape:[-1,m]}}),v=im(r.dtype),b=Vl(g,v,"prod",t);p=Be({inputs:{x:b},backend:t,attrs:{shape:f}}),l.push(g),l.push(b)}if(o){l.push(p);const f=Vn(p.shape,c);p=Be({inputs:{x:p},backend:t,attrs:{shape:f}})}return l.forEach(f=>t.disposeIntermediateTensorInfo(f)),p}const ZZ={kernelName:Ud,backendName:"webgl",kernelFunc:YZ};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function JZ(n){const{inputs:e,backend:t,attrs:s}=n,{paramsNestedSplits:r,paramsDenseValues:i,indices:o}=e,{outputRaggedRank:a}=s,l=r.map(g=>t.readSync(g.dataId)),c=r.map(g=>g.shape),u=t.readSync(i.dataId),h=t.readSync(o.dataId),[d,p,f]=jG(l,c,u,i.shape,i.dtype,h,o.shape,a),x=d.map(g=>t.makeTensorInfo([g.length],"int32",g)),m=t.makeTensorInfo(f,i.dtype,p);return x.concat([m])}const QZ={kernelName:QS,backendName:"webgl",kernelFunc:JZ};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function eJ(n){const{inputs:e,backend:t}=n,{starts:s,limits:r,deltas:i}=e,o=t.readSync(s.dataId),a=t.readSync(r.dataId),l=t.readSync(i.dataId),[c,u]=YG(o,s.shape,s.dtype,a,r.shape,l,i.shape),h=t.makeTensorInfo([c.length],"int32",c),d=t.makeTensorInfo([u.length],s.dtype,u);return[h,d]}const tJ={kernelName:eC,backendName:"webgl",kernelFunc:eJ};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nJ(n){const{inputs:e,backend:t,attrs:s}=n,{shape:r,values:i,defaultValue:o,rowPartitionTensors:a}=e,{rowPartitionTypes:l}=s,c=t.readSync(r.dataId),u=t.readSync(i.dataId),h=t.readSync(o.dataId),d=a.map(m=>t.readSync(m.dataId)),p=a.map(m=>m.shape),[f,x]=ZG(c,r.shape,u,i.shape,i.dtype,h,o.shape,d,p,l);return t.makeTensorInfo(f,i.dtype,x)}const sJ={kernelName:tC,backendName:"webgl",kernelFunc:nJ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const lk=n=>{const{backend:e,attrs:t}=n,{start:s,stop:r,step:i,dtype:o}=t,a=JG(s,r,i,o);return e.makeTensorInfo([a.length],o,a)},rJ={kernelName:j0,backendName:"webgl",kernelFunc:lk};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const iJ="return 1.0 / x;",oJ=Kt({opSnippet:iJ}),aJ={kernelName:Eu,backendName:"webgl",kernelFunc:oJ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const lJ=ri+` + return (x < 0.0) ? 0.0 : x; +`,cJ=` + vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,uJ=Kt({opSnippet:lJ,packedOpSnippet:cJ}),hJ={kernelName:ku,backendName:"webgl",kernelFunc:uJ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dJ=ri+` + return (x < 0.0) ? 0.0 : min(6.0, x); +`,pJ=` + vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,fJ=Kt({opSnippet:dJ,packedOpSnippet:pJ}),mJ={kernelName:Au,backendName:"webgl",kernelFunc:fJ};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let gJ=class{constructor(e,t,s,r,i){this.variableNames=["A"],this.outputShape=[];const[o,a,l,c]=e;this.outputShape=[o,t,s,c];const u=[r&&t>1?a-1:a,r&&s>1?l-1:l],h=[r&&t>1?t-1:t,r&&s>1?s-1:s];let d;i?d="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec2 effectiveInputOverOutputRatioRC = vec2( + ${u[0]/h[0]}, + ${u[1]/h[1]}); + const vec2 inputShapeRC = vec2(${a}.0, ${l}.0); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + ivec2 yRC = coords.yz; + + // Fractional source index. + vec2 sourceFracIndexRC = ${d}; + + // Compute the four integer indices. + ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0))); + ivec2 sourceCeilRC = ivec2( + min(inputShapeRC - 1.0, ceil(sourceFracIndexRC))); + + float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d); + float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d); + float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d); + float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d); + + vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC); + + float top = topLeft + (topRight - topLeft) * fracRC.y; + float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y; + float newValue = top + (bottom - top) * fracRC.x; + + setOutput(newValue); + } + `}};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class xJ{constructor(e,t,s,r,i){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[o,a,l,c]=e;this.outputShape=[o,t,s,c];const u=[r&&t>1?a-1:a,r&&s>1?l-1:l],h=[r&&t>1?t-1:t,r&&s>1?s-1:s];let d;i?d="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec3 effectiveInputOverOutputRatioRC = vec3( + ${u[0]/h[0]}, + ${u[1]/h[1]}, + ${u[1]/h[1]}); + const vec3 inputShapeRC = vec3(${a}.0, ${l}.0, + ${l}.0); + + float getAValue(int b, int r, int c, int d) { + return getChannel(getA(b, r, c, d), vec2(c, d)); + } + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + // Calculate values for next column in yRC.z. + ivec3 yRC = coords.yzz + ivec3(0, 0, 1); + + // Fractional source index. + vec3 sourceFracIndexRC = ${d}; + + // Compute the four integer indices. + ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0))); + ivec3 sourceCeilRC = ivec3( + min(inputShapeRC - 1.0, ceil(sourceFracIndexRC))); + + // Should we calculate next column and row elements in 2x2 packed cell. + bool hasNextCol = d < ${c-1}; + bool hasNextRow = coords.z < ${s-1}; + + // In parallel, construct four corners for all four components in + // packed 2x2 cell. + vec4 topLeft = vec4( + getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d), + hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0); + + vec4 bottomLeft = vec4( + getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d), + hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0); + + vec4 topRight = vec4( + getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d), + hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0); + + vec4 bottomRight = vec4( + getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d), + hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0); + + vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC); + + vec4 top = mix(topLeft, topRight, fracRC.yyzz); + vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz); + vec4 newValue = mix(top, bottom, fracRC.x); + + setOutput(newValue); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vJ(n){const{inputs:e,backend:t,attrs:s}=n,{images:r}=e,{alignCorners:i,halfPixelCenters:o,size:a}=s,[l,c]=a,u=oe().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new xJ(r.shape,l,c,i,o):new gJ(r.shape,l,c,i,o);return t.runWebGLProgram(u,[r],"float32")}const bJ={kernelName:Gd,backendName:"webgl",kernelFunc:vJ};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let yJ=class{constructor(e,t,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,i]=t,[,o,a]=e,l=[s&&o>1?r-1:r,s&&a>1?i-1:i],c=[s&&o>1?o-1:o,s&&a>1?a-1:a],u=l[0]/c[0],h=l[1]/c[1],d=1/u,p=1/h,f=Math.ceil(d)*2+2,x=Math.ceil(p)*2+2;this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + int r = coords[1]; + int c = coords[2]; + + float accumulator = 0.0; + + const float heightScale = float(${u}); + const float widthScale = float(${h}); + + const float invHeightScale = float(${d}); + const float invWidthScale = float(${p}); + + const int winHeight = int(${f}); + const int winWidth = int(${x}); + + // Compute bounds for where in dy we will look + float startRLerp = floor(float(r) * invHeightScale); + int startDyR = int(startRLerp - float(winHeight / 2)); + + float startCLerp = floor(float(c) * invWidthScale); + int startDyC = int(startCLerp - float(winWidth / 2)); + + // Loop over dy + for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) { + int dyR = dyROffset + startDyR; + + // Guard against the window exceeding the bounds of dy + if (dyR < 0 || dyR >= ${o}) { + continue; + } + + for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) { + int dyC = dyCOffset + startDyC; + + // Guard against the window exceeding the bounds of dy + if (dyC < 0 || dyC >= ${a}) { + continue; + } + + float dxR = float(dyR) * heightScale; + int topDxRIndex = int(floor(dxR)); + int bottomDxRIndex = int(min(ceil(dxR), ${r-1}.0)); + float dxRLerp = dxR - float(topDxRIndex); + float inverseDxRLerp = 1.0 - dxRLerp; + + float dxC = float(dyC) * widthScale; + int leftDxCIndex = int(floor(dxC)); + int rightDxCIndex = int(min(ceil(dxC), ${i-1}.0)); + float dxCLerp = dxC - float(leftDxCIndex); + float inverseDxCLerp = 1.0 - dxCLerp; + + if (r == topDxRIndex && c == leftDxCIndex) { + // topLeft + accumulator += + getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp; + } + + if (r == topDxRIndex && c == rightDxCIndex) { + // topRight + accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp; + } + + if (r == bottomDxRIndex && c == leftDxCIndex) { + // bottomLeft + accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp; + } + + if (r == bottomDxRIndex && c == rightDxCIndex) { + // bottomRight + accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp; + } + } + } + // End loop over dy + + setOutput(accumulator); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wJ(n){const{inputs:e,backend:t,attrs:s}=n,{images:r,dy:i}=e,{alignCorners:o}=s,a=new yJ(i.shape,r.shape,o);return t.runWebGLProgram(a,[i],i.dtype)}const SJ={kernelName:J0,backendName:"webgl",kernelFunc:wJ};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let CJ=class{constructor(e,t,s,r,i){this.variableNames=["A"],this.outputShape=[];const[o,a,l,c]=e;this.outputShape=[o,t,s,c];const u=[r&&t>1?a-1:a,r&&s>1?l-1:l],h=[r&&t>1?t-1:t,r&&s>1?s-1:s],d=r?"0.5":"0.0";let p;i?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec2 effectiveInputOverOutputRatioRC = vec2( + ${u[0]/h[0]}, + ${u[1]/h[1]}); + const vec2 inputShapeRC = vec2(${a}.0, ${l}.0); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + ivec2 yRC = coords.yz; + + // Fractional source index. + vec2 sourceFracIndexRC = ${p}; + + // Compute the coordinators of nearest neighbor point. + ivec2 sourceNearestRC = ivec2( + min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d}))); + float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d); + + setOutput(newValue); + } + `}};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class _J{constructor(e,t,s,r,i){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[o,a,l,c]=e;this.outputShape=[o,t,s,c];const u=[r&&t>1?a-1:a,r&&s>1?l-1:l],h=[r&&t>1?t-1:t,r&&s>1?s-1:s],d=r?"0.5":"0.0";let p;i?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec3 effectiveInputOverOutputRatioRC = vec3( + ${u[0]/h[0]}, + ${u[1]/h[1]}, + ${u[1]/h[1]}); + const vec3 inputShapeRC = vec3(${a}.0, ${l}.0, + ${l}.0); + + float getAValue(int b, int r, int c, int d) { + return getChannel(getA(b, r, c, d), vec2(c, d)); + } + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + // Calculate values for next column in yRC.z. + ivec3 yRC = coords.yzz + ivec3(0, 0, 1); + + // Fractional source index. + vec3 sourceFracIndexRC = ${p}; + + // Compute the coordinators of nearest neighbor point. + ivec3 sourceNearestRC = ivec3( + min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d}))); + + // Should we calculate next column and row elements in 2x2 packed cell. + bool hasNextCol = d < ${c-1}; + bool hasNextRow = coords.z < ${s-1}; + + vec4 newValue = vec4( + getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d), + hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0); + + setOutput(newValue); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function TJ(n){const{inputs:e,backend:t,attrs:s}=n,{images:r}=e,{alignCorners:i,halfPixelCenters:o,size:a}=s,[l,c]=a,u=oe().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new _J(r.shape,l,c,i,o):new CJ(r.shape,l,c,i,o);return t.runWebGLProgram(u,[r],r.dtype)}const IJ={kernelName:Wd,backendName:"webgl",kernelFunc:TJ};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let EJ=class{constructor(e,t,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,i]=t,[,o,a]=e,l=[s&&o>1?r-1:r,s&&a>1?i-1:i],c=[s&&o>1?o-1:o,s&&a>1?a-1:a],u=l[0]/c[0],h=l[1]/c[1],d=1/u,p=1/h,f=Math.ceil(d)*2+2,x=Math.ceil(p)*2+2;this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + int r = coords[1]; + int c = coords[2]; + + float accumulator = 0.0; + + const float heightScale = float(${u}); + const float widthScale = float(${h}); + + const float invHeightScale = float(${d}); + const float invWidthScale = float(${p}); + + const int winHeight = int(${f}); + const int winWidth = int(${x}); + + // Compute bounds for where in dy we will look + float startRLerp = floor(float(r) * invHeightScale); + int startDyR = int(floor(startRLerp - float(winHeight / 2))); + + float startCLerp = floor(float(c) * invWidthScale); + int startDyC = int(floor(startCLerp - float(winWidth / 2))); + + // Loop over dy + for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) { + int dyR = dyROffset + startDyR; + + // Guard against the window exceeding the bounds of dy + if (dyR < 0 || dyR >= ${o}) { + continue; + } + + for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) { + int dyC = dyCOffset + startDyC; + + // Guard against the window exceeding the bounds of dy + if (dyC < 0 || dyC >= ${a}) { + continue; + } + + float sourceFracRow = + float(${l[0]}) * + (float(dyR) / float(${c[0]})); + + float sourceFracCol = + float(${l[1]}) * + (float(dyC) / float(${c[1]})); + + int sourceNearestRow = int(min( + float(int(${r}) - 1), + ${s} ? float(round(sourceFracRow)) : + float(floor(sourceFracRow)))); + + int sourceNearestCol = int(min( + float(int(${i}) - 1), + ${s} ? float(round(sourceFracCol)) : + float(floor(sourceFracCol)))); + + if (r == sourceNearestRow && c == sourceNearestCol) { + accumulator += getDy(b, dyR, dyC, d); + } + } + } + // End loop over dy + + setOutput(accumulator); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kJ(n){const{inputs:e,backend:t,attrs:s}=n,{images:r,dy:i}=e,{alignCorners:o}=s,a=new EJ(i.shape,r.shape,o);return t.runWebGLProgram(a,[i],i.dtype)}const AJ={kernelName:Z0,backendName:"webgl",kernelFunc:kJ};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let RJ=class{constructor(e,t){this.variableNames=["x"];const s=e.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);if(this.outputShape=e,s===1){this.userCode=` + void main() { + int coord = getOutputCoords(); + setOutput(getX(${e[0]} - coord - 1)); + } + `;return}const r=a=>t.indexOf(a)!==-1&&e[a]!==1?`${e[a]} - coords[${a}] - 1`:`coords[${a}]`,i=e.map((a,l)=>r(l)).join(","),o=an(s);this.userCode=` + void main() { + ${o} coords = getOutputCoords(); + setOutput(getX(${i})); + } + `}};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class MJ{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const s=e.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);this.outputShape=e;const r=Os("rc",s),i=`${r[s-1]} + 1 < ${this.outputShape[s-1]}`,o=`${r[s-2]} + 1 < ${this.outputShape[s-2]}`,a=an(s);s===1?this.userCode=` + void main(){ + int rc = getOutputCoords(); + vec4 result = vec4(0.); + result.r = getChannel(getX(${e[0]} - rc - 1), + ${e[0]} - rc - 1); + if(${i}){ + result.g = getChannel(getX(${e[0]} - (rc + 1) - 1), + ${e[0]} - (rc + 1) - 1); + } + setOutput(result); + } + `:this.userCode=` + void main() { + ${a} rc = getOutputCoords(); + vec4 result = vec4(0.); + result.r = ${l(r.slice())}; + if(${i}){ + result.g = ${c(r.slice())}; + } + if(${o}) { + result.b = ${u(r.slice())}; + if(${i}) { + result.a = ${h(r.slice())}; + } + } + setOutput(result); + } + `;function l(f){return d(f)}function c(f){return f[s-1]="("+f[s-1]+" + 1)",d(f)}function u(f){return f[s-2]="("+f[s-2]+" + 1)",d(f)}function h(f){return f[s-1]="("+f[s-1]+" + 1)",f[s-2]="("+f[s-2]+" + 1)",d(f)}function d(f){const x=e.map((v,b)=>p(b,f)),m=x.join(","),g=x.slice(-2).join(",");return`getChannel(getX(${m}), vec2(${g}))`}function p(f,x){return t.indexOf(f)!==-1&&e[f]!==1?`${e[f]} - ${x[f]} - 1`:`${x[f]}`}}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function NJ(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{dims:i}=s,o=r.shape.length,a=It(i,r.shape);if(o===0)return vr({inputs:{x:r},backend:t});const l=oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new MJ(r.shape,a):new RJ(r.shape,a);return t.runWebGLProgram(l,[r],r.dtype)}const $J={kernelName:Hd,backendName:"webgl",kernelFunc:NJ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let DJ=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];const s=e[1],r=e[2];this.outputShape=e;let i="";typeof t=="number"?i=`float outputValue = ${t.toFixed(2)};`:i=` + vec3 fill = vec3(${t.join(",")}); + float outputValue = fill[coords[3]];`,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int x = coords[2]; + int y = coords[1]; + float coordXFloat = (float(x) - params[0]) * params[3] - + (float(y) - params[1]) * params[2]; + float coordYFloat = (float(x) - params[0]) * params[2] + + (float(y) - params[1]) * params[3]; + int coordX = int(round(coordXFloat + params[0])); + int coordY = int(round(coordYFloat + params[1])); + ${i} + if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${s}) { + outputValue = getImage(coords[0], coordY, coordX, coords[3]); + } + setOutput(outputValue); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const PJ={kernelName:sm,backendName:"webgl",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{image:s}=n,{radians:r,fillValue:i,center:o}=e,a=t,l=new DJ(s.shape,i),[c,u]=wm(o,s.shape[1],s.shape[2]),h=[[c,u,Math.sin(r),Math.cos(r)]];return a.runWebGLProgram(l,[s],s.dtype,h)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const LJ=` + // OpenGL ES does not support round function. + // The algorithm is based on banker's rounding. + float base = floor(x); + if ((x - base) < 0.5) { + return floor(x); + } else if ((x - base) > 0.5) { + return ceil(x); + } else { + if (mod(base, 2.0) == 0.0) { + return base; + } else { + return base + 1.0; + } + } +`,FJ=Kt({opSnippet:LJ}),OJ={kernelName:Ru,backendName:"webgl",kernelFunc:FJ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const zJ="return inversesqrt(x);",BJ=Kt({opSnippet:zJ,cpuKernelImpl:QG}),UJ={kernelName:Mu,backendName:"webgl",kernelFunc:BJ};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let nb=class{constructor(e,t,s,r,i,o,a=!0,l=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;const c=an(i.length),u=an(o.length);let h="";s===1?h="i":s===2&&(h="i, j");const d=`getIndices(${h})`;let p="";r===1?p="i":r===2&&(p="i, coords[1]");const f=`getUpdates(${p})`;let x="";l&&(x="coords[0], coords[1]");const m=`getDefaultValue(${x})`,g=t>1?"strides[j]":"strides";this.userCode=` + ${c} strides = ${c}(${i}); + + void main() { + ${u} coords = getOutputCoords(); + float sum = 0.0; + bool found = false; + for (int i = 0; i < ${e}; i++) { + int flattenedIndex = 0; + for (int j = 0; j < ${t}; j++) { + int index = round(${d}); + flattenedIndex += index * ${g}; + } + if (flattenedIndex == coords[0]) { + sum += ${f}; + found = true; + } + } + setOutput(mix(${m}, sum, float(found))); + } + `}};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class VJ{constructor(e,t,s,r,i,o,a=!0,l=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=o;const c=an(i.length),u=an(o.length);let h="";s===1?h="i":s===2&&(h="i, j");const d=`getIndices(${h})`;let p="";r===1?p="i":r===2&&(p="i, coords[1]");const f=`getUpdates(${p})`;let x="";l&&(x="coords[0], coords[1]");const m=`getDefaultValue(${x})`,g=t>1?"strides[j]":"strides",v=t>1?"strides[j + 1]":"strides";this.userCode=` + ${c} strides = ${c}(${i}); + + void main() { + ${u} coords = getOutputCoords(); + vec4 sum = vec4(0.); + vec4 found = vec4(0.); + for (int i = 0; i < ${e}; i+=2) { + ivec2 flattenedIndex = ivec2(0); + for (int j = 0; j < ${t}; j+=2) { + ivec4 index = round(${d}); + flattenedIndex += index.xz * ${g}; + if (j + 1 < ${t}) { + flattenedIndex += index.yw * ${v}; + } + } + if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] || + flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) { + vec4 updVals = ${f}; + if (flattenedIndex[0] == coords[0]) { + sum.xy += updVals.xy; + found.xy = vec2(1.); + } else if (flattenedIndex[0] == coords[0] + 1) { + sum.zw += updVals.xy; + found.zw = vec2(1.); + } + if (flattenedIndex[1] == coords[0]) { + sum.xy += updVals.zw; + found.xy = vec2(1.); + } else if (flattenedIndex[1] == coords[0] + 1) { + sum.zw += updVals.zw; + found.zw = vec2(1.); + } + } + } + setOutput(mix(${m}, sum, found)); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function WJ(n){const{inputs:e,backend:t,attrs:s}=n,{indices:r,updates:i}=e,{shape:o}=s,{sliceRank:a,numUpdates:l,sliceSize:c,strides:u,outputSize:h}=so(i,r,o),d=[h/c,c];if(h===0)return t.makeTensorInfo(o,r.dtype);const p=Be({inputs:{x:r},backend:t,attrs:{shape:[l,a]}}),f=Be({inputs:{x:i},backend:t,attrs:{shape:[l,c]}}),x=t.makeTensorInfo([],"float32",new Float32Array([0]));let m;oe().getBool("WEBGL_PACK")?m=new VJ(l,a,p.shape.length,f.shape.length,u,d):m=new nb(l,a,p.shape.length,f.shape.length,u,d);const g=t.runWebGLProgram(m,[f,p,x],f.dtype),v=Be({inputs:{x:g},backend:t,attrs:{shape:o}});return t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(x),v}const GJ={kernelName:x2,backendName:"webgl",kernelFunc:WJ};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let HJ=class{constructor(e,t,s,r){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,s];const i="while (left < right) {",o=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,a=oe().getNumber("WEBGL_VERSION")===2?i:o,l=r==="left"?"<":"<=";this.userCode=` + int findBound(int batch, float value) { + int left = 0; + int right = numInputs; + int mid; + ${a} + mid = (left + right) / 2; + if (getSortedSequence(batch, mid) ${l} value) { + left = mid + 1; + } else { + right = mid; + } + } + return right; + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int valueIndex = coords[1]; + + float value = getValues(batch, valueIndex); + + setOutput(float(findBound(batch, value))); + } + `}};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qJ(n){const{inputs:e,backend:t,attrs:s}=n,{sortedSequence:r,values:i}=e,{side:o}=s,a=new HJ(r.shape[0],r.shape[1],i.shape[1],o),l=[[r.shape[1]]];return t.runWebGLProgram(a,[r,i],"int32",l)}const XJ={kernelName:b2,backendName:"webgl",kernelFunc:qJ};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let KJ=class{constructor(e,t,s){this.variableNames=["c","a","b"],this.outputShape=t;let r,i;if(s>4)throw Error(`Where for rank ${s} is not yet supported`);if(s===1)i="resRC",r="resRC";else{const a=["resRC.x","resRC.y","resRC.z","resRC.w"],l=[],c=[];for(let u=0;u= 1.0) { + setOutput(getA(${i})); + } else { + setOutput(getB(${i})); + } + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jJ(n){const{inputs:e,backend:t}=n,{condition:s,t:r,e:i}=e,o=new KJ(s.shape.length,r.shape,r.shape.length);return t.runWebGLProgram(o,[s,r,i],ds(r.dtype,i.dtype))}const YJ={kernelName:qd,backendName:"webgl",kernelFunc:jJ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ZJ=` + // Stable and Attracting Fixed Point (0, 1) for Normalized Weights. + // see: https://arxiv.org/abs/1706.02515 + float scaleAlpha = ${ip}; + float scale = ${op}; + return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0); +`,JJ=Kt({opSnippet:ZJ}),QJ={kernelName:Nu,backendName:"webgl",kernelFunc:JJ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eQ=nh+` + return 1.0 / (1.0 + exp(-1.0 * x)); +`,tQ=` + vec4 result = 1.0 / (1.0 + exp(-1.0 * x)); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,nQ=Kt({opSnippet:eQ,packedOpSnippet:tQ,cpuKernelImpl:tH}),sQ={kernelName:Lu,backendName:"webgl",kernelFunc:nQ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rQ=` + if (isnan(x)) { return 0.0; } + return sign(x); +`,iQ=Kt({opSnippet:rQ}),oQ={kernelName:Pu,backendName:"webgl",kernelFunc:iQ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const aQ=nh+` + return sin(x); +`,lQ=` + vec4 result = sin(x); + bvec4 isNaN = isnan(x); + ${Ul} + return result; +`,cQ=Kt({opSnippet:aQ,packedOpSnippet:lQ}),uQ={kernelName:$u,backendName:"webgl",kernelFunc:cQ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hQ=` + float e2x = exp(x); + return (e2x - 1.0 / e2x) / 2.0; +`,dQ=Kt({opSnippet:hQ}),pQ={kernelName:Du,backendName:"webgl",kernelFunc:dQ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fQ=` + float epsilon = 1.1920928955078125e-7; + float threshold = log(epsilon) + 2.0; + + bool too_large = x > -threshold; + bool too_small = x < threshold; + + float result; + float exp_x = exp(x); + + if (too_large){ + result = x; + } + else if (too_small){ + result = exp_x; + } + else{ + result = log(exp_x + 1.0); + } + return result; +`,mQ=Kt({opSnippet:fQ}),gQ={kernelName:Fu,backendName:"webgl",kernelFunc:mQ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xQ=n=>{const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{blockShape:i,paddings:o}=s;N(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");const a=i.reduce((g,v)=>g*v),l=[[0,0]];l.push(...o);for(let g=1+i.length;gt.disposeIntermediateTensorInfo(g)),m},vQ={kernelName:jd,backendName:"webgl",kernelFunc:xQ};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bQ(n){const{inputs:e,backend:t}=n,{indices:s,values:r,denseShape:i,defaultValue:o}=e;if(i.shape.length!==1)throw new Error(`Dense shape must be a vector, saw: + ${i.shape}`);if(s.shape.length!==2)throw new Error(`Indices must be a matrix, saw: + ${s.shape}`);if(r.shape.length!==1)throw new Error(`Values must be a vector, saw: + ${r.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw: + ${o.shape}`);const a=t.readSync(s.dataId),l=t.readSync(r.dataId),c=t.readSync(i.dataId),u=t.readSync(o.dataId)[0],[h,d,p,f,x]=sH(a,s.shape,s.dtype,l,r.dtype,c,u);return[t.makeTensorInfo(d,s.dtype,h),t.makeTensorInfo([d[0]],r.dtype,p),t.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(m=>Number(m)))),t.makeTensorInfo([x.length],s.dtype,new Int32Array(x))]}const yQ={kernelName:nC,backendName:"webgl",kernelFunc:bQ};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wQ(n){const{inputs:e,backend:t}=n,{inputIndices:s,inputShape:r,newShape:i}=e;if(s.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${s.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${r.shape}`);if(i.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${i.shape}`);const o=Array.from(t.readSync(r.dataId)),a=t.readSync(s.dataId),l=Array.from(t.readSync(i.dataId)),[c,u,h]=rH(a,s.shape,s.dtype,o,l);return[t.makeTensorInfo(u,s.dtype,c),t.makeTensorInfo([h.length],i.dtype,new Int32Array(h))]}const SQ={kernelName:sC,backendName:"webgl",kernelFunc:wQ};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function CQ(n){const{inputs:e,backend:t}=n,{data:s,indices:r,segmentIds:i}=e;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape + ${r.shape}`);if(i.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape + ${i.shape}`);const o=t.readSync(s.dataId),a=t.readSync(r.dataId),l=t.readSync(i.dataId),[c,u]=NE(o,s.shape,s.dtype,a,l,!0);return t.makeTensorInfo(u,s.dtype,c)}const _Q={kernelName:y2,backendName:"webgl",kernelFunc:CQ};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function TQ(n){const{inputs:e,backend:t}=n,{data:s,indices:r,segmentIds:i}=e;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape + ${r.shape}`);if(i.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape + ${i.shape}`);const o=t.readSync(s.dataId),a=t.readSync(r.dataId),l=t.readSync(i.dataId),[c,u]=NE(o,s.shape,s.dtype,a,l);return t.makeTensorInfo(u,s.dtype,c)}const IQ={kernelName:w2,backendName:"webgl",kernelFunc:TQ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function EQ(n){const{inputs:e,backend:t,attrs:s}=n,{sparseIndices:r,sparseValues:i,defaultValue:o}=e,{outputShape:a}=s,{sliceRank:l,numUpdates:c,sliceSize:u,strides:h,outputSize:d}=so(i,r,a),p=!1;if(i.dtype==="string"){const g=t.bufferSync(r),v=t.bufferSync(i),b=Ci(t.readSync(o.dataId)[0]),y=eH(g,v,a,d,u,c,l,h,b,p);return t.makeTensorInfo(a,y.dtype,y.values)}const f=new nb(c,l,r.shape.length,i.shape.length,h,[d,1],p),x=t.runWebGLProgram(f,[i,r,o],i.dtype),m=Be({inputs:{x},backend:t,attrs:{shape:a}});return t.disposeIntermediateTensorInfo(x),m}const kQ={kernelName:S2,backendName:"webgl",kernelFunc:EQ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function AQ(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{numOrSizeSplits:i,axis:o}=s,a=It(o,r.shape)[0],l=Pm(r,i,a),c=r.shape.length,u=new Array(c).fill(0),h=r.shape.slice();return l.map(d=>{const p=[...h];p[a]=d;const f=sh({inputs:{x:r},backend:t,attrs:{begin:u,size:p}});return u[a]+=d,f})}const RQ={kernelName:Yd,backendName:"webgl",kernelFunc:AQ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ww="return sqrt(x);",MQ=Kt({opSnippet:ww,packedOpSnippet:ww,cpuKernelImpl:iH}),NQ={kernelName:Ou,backendName:"webgl",kernelFunc:MQ};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $Q="return x * x;",DQ=Kt({opSnippet:$Q}),PQ={kernelName:Q0,backendName:"webgl",kernelFunc:DQ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Sw="return (a - b) * (a - b);",LQ=_s({opSnippet:Sw,packedOpSnippet:Sw}),FQ={kernelName:zu,backendName:"webgl",kernelFunc:LQ};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function OQ(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e;if(r.dtype!=="string")throw new Error("Input must be of datatype string");const i=t.readSync(r.dataId),o=Ti(i),a=oH(o,"string",s);return t.makeTensorInfo(r.shape,"string",a)}const zQ={kernelName:C2,backendName:"webgl",kernelFunc:OQ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function BQ({inputs:n,attrs:e,backend:t}){const{x:s}=n,r=ri+` + return x > 0.0 ? 1.0 : float(${e.alpha}); + `,i=new Vi(s.shape,r);return t.runWebGLProgram(i,[s],s.dtype)}const UQ={kernelName:Gu,backendName:"webgl",kernelFunc:BQ};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let VQ=class{constructor(e,t,s){this.variableNames=["x"],this.outputShape=s;const r=s.length,i=an(s.length),o=an(s.length);let a="";if(r===1)a="coords * strides + begin";else{let l=0;a=s.map((c,u)=>(l++,s.length===1?`coords * strides[${u}] + begin[${u}]`:`coords[${l-1}] * strides[${u}] + begin[${u}]`)).join(",")}this.userCode=` + ${i} begin = ${i}(${e}); + ${i} strides = ${i}(${t}); + + void main() { + ${o} coords = getOutputCoords(); + setOutput(getX(${a})); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function WQ(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{begin:i,end:o,strides:a,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:h,shrinkAxisMask:d}=s,{finalShapeSparse:p,finalShape:f,isIdentity:x,sliceDim0:m,isSimpleSlice:g,begin:v,end:b,strides:y}=pv(r.shape,i,o,a,l,c,u,h,d);let w;if(x)w=Be({inputs:{x:r},backend:t,attrs:{shape:f}});else if(m||g){N(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);const T=dv(v,b,y),E=sh({inputs:{x:r},backend:t,attrs:{begin:v,size:T}});w=Be({inputs:{x:E},backend:t,attrs:{shape:f}}),t.disposeIntermediateTensorInfo(E)}else if(t.shouldExecuteOnCPU([r])){const E=t.readSync(r.dataId),R=Tt(r.shape,r.dtype,E),_=aH(p,R,y,v);w=t.makeTensorInfo(f,r.dtype,_.values)}else{const E=new VQ(v,y,p);w=t.runWebGLProgram(E,[r],r.dtype)}const C=Be({inputs:{x:w},backend:t,attrs:{shape:f}});return t.disposeIntermediateTensorInfo(w),C}const GQ={kernelName:em,backendName:"webgl",kernelFunc:WQ};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function HQ(n){const{inputs:e,backend:t,attrs:s}=n,{separator:r,nGramWidths:i,leftPad:o,rightPad:a,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:h}=e,d=t.readSync(u.dataId),p=t.readSync(h.dataId),[f,x]=lH(d,p,r,i,o,a,l,c);return[t.makeTensorInfo([f.length],"string",f),t.makeTensorInfo(h.shape,"int32",x)]}const qQ={kernelName:_2,backendName:"webgl",kernelFunc:HQ};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function XQ(n){const{inputs:e,backend:t,attrs:s}=n,{skipEmpty:r}=s,{input:i,delimiter:o}=e;if(i.dtype!=="string")throw new Error("Input must be of datatype string");if(i.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${i.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);const a=t.readSync(i.dataId),l=t.readSync(o.dataId)[0],[c,u,h]=cH(a,l,r),d=u.length;return[t.makeTensorInfo([d,2],"int32",c),t.makeTensorInfo([d],"string",u),t.makeTensorInfo([2],"int32",new Int32Array(h))]}const KQ={kernelName:rC,backendName:"webgl",kernelFunc:XQ};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jQ(n){const{inputs:e,backend:t,attrs:s}=n,{numBuckets:r}=s,{input:i}=e;if(i.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");const o=t.readSync(i.dataId),a=uH(o,r);return t.makeTensorInfo(i.shape,"int32",a)}const YQ={kernelName:iC,backendName:"webgl",kernelFunc:jQ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ZQ="return tan(x);",JQ=Kt({opSnippet:ZQ}),QQ={kernelName:Uu,backendName:"webgl",kernelFunc:JQ};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eee=` + float e2x = exp(-2.0 * abs(x)); + return sign(x) * (1.0 - e2x) / (1.0 + e2x); +`,tee=Kt({opSnippet:eee}),nee={kernelName:Vu,backendName:"webgl",kernelFunc:tee};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function see(n){const{inputs:e,backend:t,attrs:s}=n,{tensor:r,indices:i,updates:o}=e,{sliceRank:a,numUpdates:l,sliceSize:c,strides:u,outputSize:h}=so(o,i,r.shape),d=[h/c,c];if(h===0)return t.makeTensorInfo(r.shape,i.dtype);const p=Be({inputs:{x:i},backend:t,attrs:{shape:[l,a]}}),f=Be({inputs:{x:o},backend:t,attrs:{shape:[l,c]}}),x=Be({inputs:{x:r},backend:t,attrs:{shape:d}}),m=new nb(l,a,p.shape.length,f.shape.length,u,d,!1,!0),g=t.runWebGLProgram(m,[f,p,x],x.dtype),v=Be({inputs:{x:g},backend:t,attrs:{shape:r.shape}});return t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(x),t.disposeIntermediateTensorInfo(g),v}const ree={kernelName:v2,backendName:"webgl",kernelFunc:see};/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let iee=class{constructor(e,t){this.variableNames=["A"];const s=new Array(e.length);for(let o=0;o5)throw Error(`Tile for rank ${e} is not yet supported`);if(e===1)return`imod(resRC, ${n[0]})`;const t=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],s=[];for(let r=0;r5){const l=t.readSync(r.dataId),c=r.dtype==="string"?l.map(d=>Ci(d)):l,u=Tt(r.shape,r.dtype,c),h=dH(u,i);return t.makeTensorInfo(h.shape,h.dtype,h.values)}const o=new iee(r.shape,i);return t.runWebGLProgram(o,[r],r.dtype)}const aee={kernelName:Wu,backendName:"webgl",kernelFunc:ck};let lee=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int elemIdx = coords[1]; + + // We compare elements pair-wise within a group of size 2 * inc. + // The comparing rule for each group alternates between ascending + // and descending. Within each group, we compare each pair at + // positions i and i+inc. To decide whether an element at position i + // is x0 or x1, we mod it by 2 * inc, if the result is smaller than + // inc, it is in the first half of the group, we denote it as x0, + // otherwise we denote it as x1. + // For example, as shown in the Bitonic top K paper referenced above, + // Figure5(a) shows that element[1] is in the + // second half of the group when group size is 2, but it is in the + // first half of the group when group size is 4. + + bool isFirstInPair = imod(elemIdx, 2 * inc) < inc; + int i = isFirstInPair ? elemIdx : elemIdx - inc; + + int i0 = firstPass == 1 ? i : int(getIndices(batch, i)); + int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc)); + float x0 = i0 < n ? getX(batch, i0) : negativeInf; + float x1 = i1 < n ? getX(batch, i1) : negativeInf; + + // Denotes which direction indices are in (ascending or descending). + bool reverse = imod(elemIdx, 2 * dir) >= dir; + bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0); + if (reverse == isGreater) { // Elements in opposite order of direction + int iTemp = i0; + i0 = i1; + i1 = iTemp; + } + if (isFirstInPair) { + setOutput(float(i0)); + } else { + setOutput(float(i1)); + } + } + `}},cee=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode=` + void main() { + // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ... + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int elemIdx = coords[1]; + + // The output size is half of the previous size. + // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4), + // we only need to output the indices at positions |, the indices at + // positions _ can be thrown away, see Figure5(b) After Phase 2 + // (Merge phase) in the Bitonic Top K paper referenced above. + // For example, the paper shows we only need to output the orange bars. + // The output sequence should look like this | | | | | | | |. + // Because the sequence is halved, to map the output index back + // to the previous sequence to find the corresponding value, + // we need to double the index. When we double the index, + // we basically interpolate a position, so 2i looks like + // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position + // of each 2k positions by - elemIdx % k. E.g. for output at + // index 4,5,6,7, we want to get the corresponding element at + // original index 8,9,10,11, for output at index 8,9,10,11, + // we want to get the corresponding element at original index + // 16,17,18,19, so on and so forth. + + int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k)); + int i0 = firstPass == 1 ? i : int(getIndices(batch, i)); + int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k)); + + float x0 = getX(batch, i0); + float x1 = i1 < n ? getX(batch, i1) : x0; + + setOutput(x0 >= x1 ? float(i0) : float(i1)); + } + `}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Pa(n,e){e!==null&&n.disposeIntermediateTensorInfo(e)}function Cw(n){let e=1;for(;el){const _=t.readSync(r.dataId),[k,F]=pH(_,c,r.dtype,i,o);return[t.makeTensorInfo(k.shape,k.dtype,k.values),t.makeTensorInfo(F.shape,F.dtype,F.values)]}if(i===0)return c[c.length-1]=0,[t.makeTensorInfo(c,r.dtype,[]),t.makeTensorInfo(c,"int32",[])];if(u===1)return[r,yp({attrs:{shape:c,dtype:"int32",value:0},backend:t})];const h=t.texData.get(r.dataId),d=h!==null&&h.isPacked,p=d?t.unpackTensor(r):r,x=re(c)/u,m=Be({inputs:{x:p},attrs:{shape:[x,u]},backend:t});d&&Pa(t,p);const g=Cw(i),v=Cw(u);let b=null;const y=()=>b===null?[m,m]:[m,b],w=(_,k,F)=>{const B=y(),M=new lee(F),L=[[u],[b===null?1:0],[Number.NEGATIVE_INFINITY],[_],[k]],q=b;b=t.runWebGLProgram(M,B,"int32",L),Pa(t,q)};for(let _=1;_=1;F/=2)w(k,F,[x,v])}for(let _=v;_>g;_/=2){const k=y(),F=new cee([x,_/2]),M=[[u],[b===null?1:0],[g]],P=b;b=t.runWebGLProgram(F,k,"int32",M),Pa(t,P);const L=g/2,q=L*2;for(let U=L;U>=1;U/=2)w(q,U,b.shape)}let C=b;b=sh({inputs:{x:b},backend:t,attrs:{begin:0,size:[x,i]}}),Pa(t,C);let T=tk({inputs:{x:m,indices:b},backend:t,attrs:{axis:1,batchDims:1}});Pa(t,m);const E=c.slice(0,-1);E.push(i),C=b,b=Be({inputs:{x:b},attrs:{shape:E},backend:t}),Pa(t,C);const R=T;return T=Be({inputs:{x:T},attrs:{shape:E},backend:t}),Pa(t,R),[T,b]}const hee={kernelName:tm,backendName:"webgl",kernelFunc:uee};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let dee=class{constructor(e,t,s,r,i,o){this.variableNames=["Image","Transforms"],this.outputShape=o;const a=s==="nearest"?1:2;let l;switch(r){case"constant":l=1;break;case"reflect":l=2;break;case"wrap":l=3;break;case"nearest":l=4;break;default:l=1;break}this.userCode=` + float mapCoord(float outCoord, float len) { + float inCoord = outCoord; + if(${l} == 2) { + if (inCoord < 0.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz2 = 2.0 * len; + if (inCoord < sz2) { + inCoord = sz2 * float(int(float(-inCoord / sz2))) + + inCoord; + } + inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0; + } + } else if (inCoord > len - 1.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz2 = 2.0 * len; + inCoord -= sz2 * float(int(float(inCoord / sz2))); + if (inCoord >= len) { + inCoord = sz2 - inCoord - 1.0; + } + } + } + return clamp(inCoord, 0.0, len - 1.0); + } else if (${l} == 3) { + if (inCoord < 0.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz = len - 1.0; + inCoord += len * (float(int(float(-inCoord / sz))) + 1.0); + } + } else if (inCoord > len - 1.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz = len - 1.0; + inCoord -= len * float(int(float(inCoord / sz))); + } + } + return clamp(inCoord, 0.0, len - 1.0); + } else if (${l} == 4) { + return clamp(outCoord, 0.0, len - 1.0); + } else { + return outCoord; + } + } + + float readWithFillValue(int batch, int coordY, int coordX, + int channel) { + float outputValue; + if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) { + outputValue = getImage(batch, coordY, coordX, channel); + } else { + outputValue = float(${i}); + } + return outputValue; + } + + void main() { + ivec4 coords = getOutputCoords(); + float outputValue; + int batch = coords[0]; + int x = coords[2]; + int y = coords[1]; + int channel = coords[3]; + float xf = float(x); + float yf = float(y); + float a1 = getTransforms(batch, 0); + float a2 = getTransforms(batch, 1); + float a3 = getTransforms(batch, 2); + float b1 = getTransforms(batch, 3); + float b2 = getTransforms(batch, 4); + float b3 = getTransforms(batch, 5); + float c1 = getTransforms(batch, 6); + float c2 = getTransforms(batch, 7); + float projection = c1 * xf + c2 * yf + 1.0; + if (projection == 0.0) { + outputValue = float(${i}); + } else { + float inX = (a1 * xf + a2 * yf + a3) / projection; + float inY = (b1 * xf + b2 * yf + b3) / projection; + float mapX = mapCoord(inX, float(${t})); + float mapY = mapCoord(inY, float(${e})); + + if (${a} == 1) { + int coordY = int(round(mapY)); + int coordX = int(round(mapX)); + outputValue = readWithFillValue(batch, coordY, coordX, + channel); + } else { + float yFloor = floor(mapY); + float xFloor = floor(mapX); + float yCeil = yFloor + 1.0; + float xCeil = xFloor + 1.0; + float valueYFloor = (xCeil - mapX) * + readWithFillValue(batch, int(yFloor), int(xFloor), channel) + + (mapX - xFloor) * + readWithFillValue(batch, int(yFloor), int(xCeil), channel); + float valueYCeil = (xCeil - mapX) * + readWithFillValue(batch, int(yCeil), int(xFloor), channel) + + (mapX - xFloor) * + readWithFillValue(batch, int(yCeil), int(xCeil), channel); + outputValue = (yCeil - mapY) * valueYFloor + + (mapY - yFloor) * valueYCeil; + } + } + setOutput(outputValue); + } + `}};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pee(n){const{inputs:e,backend:t,attrs:s}=n,{image:r,transforms:i}=e,{interpolation:o,fillMode:a,fillValue:l,outputShape:c}=s,[u,h,d,p]=r.shape,[f,x]=c??[h,d],m=[u,f,x,p],g=new dee(h,d,o,a,l,m);return t.runWebGLProgram(g,[r,i],"float32")}const fee={kernelName:nm,backendName:"webgl",kernelFunc:pee};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mee(n){const{inputs:e,attrs:t,backend:s}=n,{axis:r}=t,{x:i}=e;xp(i,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const o=s.readSync(i.dataId),{outputValues:a,outputShape:l,indices:c}=fH(o,r,i.shape,i.dtype);return[s.makeTensorInfo(l,i.dtype,a),s.makeTensorInfo([c.length],"int32",c)]}const gee={kernelName:T2,backendName:"webgl",kernelFunc:mee};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xee(n){const{inputs:e,backend:t,attrs:s}=n,{value:r}=e;let{axis:i}=s;i<0&&(i+=r.shape.length);const o=r,a=o.shape.length,l=r.shape[i],c=new Array(a-1);let u=0;for(let x=0;xt.disposeIntermediateTensorInfo(x)),f}const vee={kernelName:Jd,backendName:"webgl",kernelFunc:xee};/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class bee{constructor(e,t){this.variableNames=["x","segmentIds"];const s=e.windowSize,r=e.batchSize,i=e.inSize,o=e.numSegments,a=o*Math.ceil(i/s);this.outputShape=[r,a];const l="0.0",c="sumValue",u=Math.floor(s/4)*4,h=s%4,d=` + sumValue += dot(values, segFilter); + `;let p="";i%s>0&&(p=` + if (inIdx < 0 || inIdx >= ${i}) { + return initializationValue; + } + `);let f="";i%s>0&&(f=` + if (inIdx < 0 || inIdx >= ${i}) { + return -1.0; + } + `),this.userCode=` + const float initializationValue = ${l}; + + float getValue(int batch, int inIdx) { + ${p} + return getX(batch, inIdx); + } + + float getSegmentIdAtIndex(int inIdx) { + ${f} + return getSegmentIds(inIdx); + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = int(floor(float(outIdx) / float( + ${o})) * float(${s})); + int currentSeg = int(mod(float(outIdx), float(${o}))); + + float sumValue = 0.0; + + for (int i = 0; i < ${u}; i += 4) { + int inIdx = inOffset + i; + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + getValue(batch, inIdx + 3) + ); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0 + ); + + ${d} + } + + int inIdx = inOffset + ${u}; + if (${h===1}) { + vec4 values = vec4( + getValue(batch, inIdx), + initializationValue, + initializationValue, + initializationValue + ); + + int inIdxSeg = int(getSegmentIdAtIndex(inIdx)); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + 0, + 0, + 0 + ); + + ${d} + } else if (${h===2}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + initializationValue, + initializationValue + ); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, + 0, + 0 + ); + + ${d} + } else if (${h===3}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + initializationValue + ); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0, + 0 + ); + + ${d} + } + setOutput(${c}); + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yee(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,segmentIds:i}=e,{numSegments:o}=s,a=r.shape.length,l=[];let c=0;const u=ln([c],a);let h=r;u!=null&&(h=Us({inputs:{x:r},backend:t,attrs:{perm:u}}),l.push(h),c=xn(1,a)[0]);const d=W4(h.shape,c,o),p=re([h.shape[c]]),f=Be({inputs:{x:h},backend:t,attrs:{shape:[-1,p]}});l.push(f);const x=im(r.dtype),m=(y,w,C,T,E)=>{const R=y.shape[0],_=y.shape[1],k=i7(_,E),F={windowSize:k,inSize:_,batchSize:R,numSegments:E},B=new bee(F,w),M=t.compileAndRun(B,[y,C],T);if(l.push(M),M.shape[1]===E)return M;const P=lk({backend:t,attrs:{start:0,stop:E,step:1,dtype:"float32"}}),L=ck({inputs:{x:P},backend:t,attrs:{reps:[_/k]}});return l.push(P),l.push(L),m(M,w,L,T,E)},g=m(f,"unsortedSegmentSum",i,x,o),v=Be({inputs:{x:g},backend:t,attrs:{shape:d}});let b=v;if(u!=null){l.push(v);const y=no(u);b=Us({inputs:{x:b},backend:t,attrs:{perm:y}})}return l.forEach(y=>t.disposeIntermediateTensorInfo(y)),b}const wee={kernelName:Qd,backendName:"webgl",kernelFunc:yee};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const See=[iq,aq,uq,pq,mq,vq,yq,Sq,Iq,kq,Mq,Dq,Fq,Uq,Gq,qq,Kq,Jq,eX,nX,oX,pX,mX,bX,wX,EX,AX,$X,VH,LX,UX,HX,ZX,eK,nK,rK,oK,uK,pK,gK,vK,yK,SK,TK,EK,MK,$K,LK,zK,UK,HK,jK,QK,nj,ij,oj,lj,uj,dj,fj,gj,yj,Cj,Ij,kj,Mj,Dj,Oj,Vj,UH,Gj,zX,Xj,Yj,Qj,GH,sY,aY,cY,pY,gY,yY,CY,EY,MY,DY,LY,BY,VY,GY,KY,YY,JY,eZ,nZ,oZ,uZ,fZ,SZ,XH,IZ,AZ,NZ,PZ,CX,OZ,BZ,VZ,HZ,jZ,qH,ZZ,QZ,tJ,sJ,rJ,_X,vZ,aJ,hJ,mJ,jH,bJ,SJ,IJ,AJ,$J,PJ,OJ,UJ,GJ,XJ,YJ,QJ,sQ,oQ,uQ,pQ,hX,yZ,gQ,vQ,yQ,SQ,_Q,IQ,kQ,RQ,NQ,PQ,FQ,zQ,UQ,GQ,qQ,KQ,YQ,bZ,nq,QQ,nee,ree,aee,hee,fee,sq,gee,vee,wee,zZ];for(const n of See)E2(n);/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Lr=oe();Lr.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",()=>15);Lr.registerFlag("WEBGPU_CPU_FORWARD",()=>!0);Lr.registerFlag("WEBGPU_MATMUL_PROGRAM_TYPE",()=>-1);Lr.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",()=>!0);Lr.registerFlag("WEBGPU_USE_LOW_POWER_GPU",()=>!1);Lr.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e3);Lr.registerFlag("WEBGPU_USE_PROFILE_TOOL",()=>!1);Lr.registerFlag("WEBGPU_IMPORT_EXTERNAL_TEXTURE",()=>!0);Lr.registerFlag("WEBGPU_USE_NAIVE_CONV2D_DEBUG",()=>!1);Lr.registerFlag("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL",()=>-1);Lr.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER",()=>!1);Lr.registerFlag("WEBGPU_PRINT_SHADER",()=>"");Lr.registerFlag("WEBGPU_ENGINE_COMPILE_ONLY",()=>!1);/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Cee{constructor(e){e&&(this.vendor=e.vendor,this.architecture=e.architecture,this.intelGPUGeneration=this.getIntelGPUGeneration())}getIntelGPUGeneration(){if(this.isIntel()){if(this.architecture.startsWith("gen"))return Number(this.architecture.match(/\d+/));if(this.architecture.startsWith("xe"))return 12}return 0}isIntel(){return this.vendor==="intel"}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class _ee{constructor(e){this.device=e,this.numUsedBuffers=0,this.numFreeBuffers=0,this.freeBuffers=new Map,this.usedBuffers=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}acquireBuffer(e,t,s=!1,r=!0){let i;const o=_w(e,t);return r?(this.freeBuffers.has(o)||this.freeBuffers.set(o,[]),this.freeBuffers.get(o).length>0?(i=this.freeBuffers.get(o).pop(),this.numFreeBuffers--):(i=this.device.createBuffer({size:e,usage:t,mappedAtCreation:s}),this.numBytesAllocated+=e)):(i=this.device.createBuffer({size:e,usage:t,mappedAtCreation:s}),this.numBytesAllocated+=e),this.usedBuffers.has(o)||this.usedBuffers.set(o,[]),this.usedBuffers.get(o).push(i),this.numUsedBuffers++,this.numBytesUsed+=e,i}releaseBuffer(e,t=!0){if(this.freeBuffers.size===0)return;const s=e.size,r=e.usage,i=_w(s,r),o=this.usedBuffers.get(i),a=o.indexOf(e);if(a<0)throw new Error("Cannot find the buffer in buffer manager");o[a]=o[o.length-1],o.pop(),this.numUsedBuffers--,this.numBytesUsed-=s,t?(this.freeBuffers.get(i).push(e),this.numFreeBuffers++):(e.destroy(),this.numBytesAllocated-=s)}getNumUsedBuffers(){return this.numUsedBuffers}getNumFreeBuffers(){return this.numFreeBuffers}dispose(){this.freeBuffers.forEach((e,t)=>{e.forEach(s=>{s.destroy()})}),this.usedBuffers.forEach((e,t)=>{e.forEach(s=>{s.destroy()})}),this.freeBuffers=new Map,this.usedBuffers=new Map,this.numUsedBuffers=0,this.numFreeBuffers=0,this.numBytesUsed=0,this.numBytesAllocated=0}}function _w(n,e){return`${n}_${e}`}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Tee{constructor(e){this.device=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures=new Map,this.usedTextures=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}acquireTexture(e,t,s,r){const i=Iw(s),o=e*t*i,a=Tw(e,t,s,r);if(this.freeTextures.has(a)||this.freeTextures.set(a,[]),this.usedTextures.has(a)||this.usedTextures.set(a,[]),this.numBytesUsed+=o,this.numUsedTextures++,this.freeTextures.get(a).length>0){this.numFreeTextures--;const c=this.freeTextures.get(a).shift();return this.usedTextures.get(a).push(c),c}this.numBytesAllocated+=o;const l=this.device.createTexture({size:[e,t],format:s,usage:r});return this.usedTextures.get(a).push(l),l}releaseTexture(e){if(this.freeTextures.size===0)return;const t=e.width,s=e.height,r=e.format,i=e.usage,o=Tw(t,s,r,i);this.freeTextures.has(o)||this.freeTextures.set(o,[]),this.freeTextures.get(o).push(e),this.numFreeTextures++,this.numUsedTextures--;const a=this.usedTextures.get(o),l=a.indexOf(e);if(l<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(l,1);const c=Iw(r),u=t*s*c;this.numBytesUsed-=u}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){this.freeTextures.forEach((e,t)=>{e.forEach(s=>{s.destroy()})}),this.usedTextures.forEach((e,t)=>{e.forEach(s=>{s.destroy()})}),this.freeTextures=new Map,this.usedTextures=new Map,this.numUsedTextures=0,this.numFreeTextures=0,this.numBytesUsed=0,this.numBytesAllocated=0}}function Tw(n,e,t,s){return`${n}_${e}_${t}_${s}`}function Iw(n){if(n==="rgba8unorm")return 16;throw new Error(`${n} is not supported!`)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Iee(n,e){if(Math.max(...n)>5)throw new Error("Cannot symbolically compute strides for rank > 6 tensor.");const t=n.length,s="xyzwuv",r=n.map(o=>`${e}.${s[o]}`),i=new Array(t-1);i[t-2]=r[t-1];for(let o=t-3;o>=0;--o)i[o]=`(${i[o+1]} * ${r[o+1]})`;return i}const Aa=(n,e,t)=>t==="int32"?`atomicAdd(${n}, bitcast(${e}));`:` + { + var oldValue = 0; + loop { + let newValueF32 = bitcast(oldValue) + (${e}); + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(${n}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Bc;(function(n){n[n.FROM_PIXELS=0]="FROM_PIXELS",n[n.DRAW=1]="DRAW"})(Bc||(Bc={}));const Eee=(n,e,t,s,r)=>{const i={dtype:s.dtype,shape:s.shape},o=Aee(t,i,e),a=n.createShaderModule({code:o,label:e.constructor.name});let l=oe().get("WEBGPU_PRINT_SHADER");if(l!==""){l=l.toLowerCase();const c=l.split(",");(l==="all"||c.some(u=>e.shaderKey.toLowerCase().includes(u)))&&(console.group(e.shaderKey),console.debug(o),console.groupEnd())}return r?n.createComputePipelineAsync({compute:{module:a,entryPoint:"_start"},label:e.constructor.name,layout:"auto"}):n.createComputePipeline({compute:{module:a,entryPoint:"_start"},label:e.constructor.name,layout:"auto"})},Rt=(n,e="f32")=>{switch(n){case 1:return`${e}`;case 2:return`vec2<${e}>`;case 3:return`vec3<${e}>`;case 4:return`vec4<${e}>`;default:throw new Error(`${n}-component ${e} is not supported.`)}};function zn(n){if(n<=1)return"i32";if(n===2)return"vec2";if(n===3)return"vec3";if(n===4)return"vec4";if(n===5)return"vec5";if(n===6)return"vec6";throw Error(`GPU for rank ${n} is not yet supported`)}function Io(n){if(n===0)return"x";if(n===1)return"y";if(n===2)return"z";if(n===3)return"w";if(n===4)return"u";if(n===5)return"v";throw Error(`Index ${n} is not yet supported`)}function De(...n){let e;switch(n.length){case 0:e=` + fn main() + `;break;case 1:e=` + fn main(${n[0]} : i32) + `;break;default:throw Error("Unreachable")}return e}function Ew(n,e){let t;return t=` + ${kee(e)} + fn _start(@builtin(local_invocation_id) LocalId : vec3, + @builtin(global_invocation_id) GlobalId : vec3, + @builtin(local_invocation_index) LocalIndex: u32, + @builtin(workgroup_id) WorkgroupId : vec3, + @builtin(num_workgroups) NumWorkgroups : vec3) { + localId = LocalId; + localIndex = LocalIndex; + globalId = GlobalId; + numWorkgroups = NumWorkgroups; + workgroupId = WorkgroupId; + ${n?"main(getGlobalIndex());":"main();"}; + } + `,t}function kee(n){return` + @compute @workgroup_size(${n.workgroupSize[0]}, ${n.workgroupSize[1]}, ${n.workgroupSize[2]}) +`}function Aee(n,e,t){const s=[],r=t.workgroupSize[0]*t.workgroupSize[1]*t.workgroupSize[2];if(t.outputComponent=t.outputComponent?t.outputComponent:1,s.push(` + + var localId: vec3; + var localIndex: u32; + var globalId: vec3; + var numWorkgroups: vec3; + var workgroupId: vec3; + + // Only used when the y/z dimension of workgroup size is 1. + fn getGlobalIndex() -> i32 { + ${uk(t)?" return i32(globalId.x);":` return i32((workgroupId.z * numWorkgroups.x * numWorkgroups.y + + workgroupId.y * numWorkgroups.x + workgroupId.x) * ${r}u + + localIndex); + `} + } + `),t.pixelsOpType!=null){const f=t.pixelsOpType===Bc.FROM_PIXELS?`@group(0) @binding(0) var result: array<${Ya(e.dtype,t.outputComponent)}>;`:`@group(0) @binding(1) var inBuf : array<${Ya(n[0].dtype,t.outputComponent)}>;`,x=e.shape.length===3?"vec2":"i32";s.push(` + struct Uniform { + outShapeStrides : ${x}, + size : i32, + numChannels : i32, + alpha : f32, + }; + + ${f} + @group(0) @binding(2) var uniforms: Uniform; + `);const m=Aw(t);return[kw,s.join(` +`),Tf(e.shape),t.getUserCode(),Ew(m,t)].join(` +`)}let i,o,a="struct Uniforms { NAN : f32, INFINITY : f32, ";t.variableNames.forEach((f,x)=>{const m=zn(n[x].shape.length);a+=`${f.charAt(0).toLowerCase()+f.slice(1)}Shape : ${m}, `,i=n[x].shape.length-1,o=zn(i),a+=`${f.charAt(0).toLowerCase()+f.slice(1)}ShapeStrides: ${o}, `});const l=zn(e.shape.length);a+=`outShape : ${l}, `,i=e.shape.length-1,o=zn(i),a+=` + outShapeStrides: ${o}, `,t.size&&(a+="size : i32, "),t.uniforms&&(a+=t.uniforms),a+="};",a=Oee(a),s.push(a),t.atomic?s.push(` + @group(0) @binding(0) var result: array>; + `):s.push(` + @group(0) @binding(0) var result: array<${Ya(e.dtype,t.outputComponent)}>; + `),t.variableNames.forEach((f,x)=>{s.push(` + @group(0) @binding(${1+x}) var ${f}: array<${t.variableComponents?Ya(n[x].dtype,t.variableComponents[x]):Ya(n[x].dtype,t.outputComponent)}>; + `)}),a!==""&&s.push(` + @group(0) @binding(${1+t.variableNames.length}) var uniforms: Uniforms; + `);const c=Pee(e.shape,t.dispatchLayout),u=[kw,s.join(` +`)+Mee,Tf(e.shape),c,Lee(e.shape.length)];t.atomic||u.push(Fee(e.shape,e.dtype,t.outputComponent)),t.variableNames.forEach((f,x)=>{u.push(`${Tf(n[x].shape,f)}`)});const h=n.map((f,x)=>Dee(f,e.shape,t.variableComponents?t.variableComponents[x]:t.outputComponent,t.dispatchLayout.x.length===e.shape.length)).join(` +`);u.push(h),u.push(t.getUserCode());const d=Aw(t);return u.push(Ew(d,t)),u.join(` +`)}function Ree(n,e,t){let s=n.shaderKey;if(n.pixelsOpType!=null)return s;const r=[],i=[];e.forEach(u=>{r.push(u.shape),i.push(u.dtype)}),r.push(t.shape),i.push(t.dtype);const o=e.map(u=>oa(u.shape,t.shape)),a=e.map(u=>Wt(u.shape,t.shape)).join("_"),l=o.map(u=>u.join("_")).join(";"),c=uk(n)?"flatDispatch":"";return s+="_"+(n.workgroupSize?n.workgroupSize.join(","):"")+r.map(u=>u.length).join(",")+i.join(",")+n.variableNames.join(",")+l+a+c,s}const kw=` + struct vec5 {x: i32, y: i32, z: i32, w: i32, u: i32}; + struct vec6 {x: i32, y: i32, z: i32, w: i32, u: i32, v: i32}; + + // Checks whether coordinates lie within the bounds of the shape. + fn coordsInBounds2D(coord : vec2, shape : vec2) -> bool { + return all(coord >= vec2(0)) && all(coord < shape); + } + fn coordsInBounds3D(coord : vec3, shape : vec3) -> bool { + return all(coord >= vec3(0)) && all(coord < shape); + } + fn coordsInBounds4D(coord : vec4, shape : vec4) -> bool { + return all(coord >= vec4(0)) && all(coord < shape); + } + + fn getIndexFromCoords1D(coord : i32, shape : i32) -> i32 { + return coord; + } + fn getIndexFromCoords2D(coords : vec2, shape : vec2) -> i32 { + return dot(coords, vec2(shape.y, 1)); + } + fn getIndexFromCoords3D(coords : vec3, shape : vec3) -> i32 { + return dot(coords, vec3(shape.y * shape.z, shape.z, 1)); + } + fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { + return dot(coords, vec4( + shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); + } + fn getIndexFromCoords5D(coords : vec5, shape : vec5) -> i32 { + let shapeStrides: vec5 = vec5(shape.y * shape.z * shape.w * shape.u, shape.z * shape.w * shape.u, shape.w * shape.u, shape.u, 1); + return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u; + } + fn getIndexFromCoords6D(coords : vec6, shape : vec6) -> i32 { + let shapeStrides: vec6 = vec6(shape.y * shape.z * shape.w * shape.u * shape.v, shape.z * shape.w * shape.u * shape.v, shape.w * shape.u * shape.v, shape.u * shape.v, shape.v, 1); + return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u + coords.v*shapeStrides.v; + } + + // NaN defination in IEEE 754-1985 is : + // - sign = either 0 or 1. + // - biased exponent = all 1 bits. + // - fraction = anything except all 0 bits (since all 0 bits represents infinity). + // https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers + fn isnan(val: f32) -> bool { + let floatToUint: u32 = bitcast(val); + return (floatToUint & 0x7fffffffu) > 0x7f800000u; + } + fn isnanVec4(val : vec4) -> vec4 { + let floatToUint: vec4 = bitcast>(val); + return (floatToUint & vec4(0x7fffffffu)) > vec4(0x7f800000u); + } +`,Mee=` + fn isinf(val: f32) -> bool { + return abs(val) == uniforms.INFINITY; + } +`;function Tf(n,e=""){const t=n.length,s=e!==""?`get${e.charAt(0).toUpperCase()+e.slice(1)}CoordsFromIndex`:"getCoordsFromIndex",r=e!==""?`${e.charAt(0).toLowerCase()+e.slice(1)}ShapeStrides`:"outShapeStrides";if(t<=1)return`fn ${s}(index : i32) -> i32 { return index; }`;const i=it(n),o=zn(t),a=[];for(let c=0;c vec2 { + let d0 = index / uniforms.${r}; let d1 = index - d0 * uniforms.${r}; + return vec2(d0, d1); + }`;let l;return l="var index2 = index;"+i.map((c,u)=>{const h=`let ${a[u]} = index2 / uniforms.${r}.${Io(u)}`,d=u===i.length-1?`let ${a[u+1]} = index2 - ${a[u]} * uniforms.${r}.${Io(u)}`:`index2 = index2 - ${a[u]} * uniforms.${r}.${Io(u)}`;return`${h}; ${d};`}).join(""),` + fn ${s}(index : i32) -> ${o} { + ${l} + return ${o}(${a.join(",")}); + } + `}function Nee(n,e){const t=n.name,s=n.shape.length,r=zn(s),i="get"+t.charAt(0).toUpperCase()+t.slice(1),o=["d0","d1","d2","d3","d4","d5"].slice(0,s),a=o.map(u=>`${u} : i32`).join(", ");if(s<1)return` + fn ${i}() -> ${Rt(e)} { + return ${Rt(e)}(${t}[0]); + } + `;const l=`uniforms.${t.charAt(0).toLowerCase()+t.slice(1)}Shape`;let c=`${s}D`;return s===0&&(c="1D"),` + fn ${i}(${a}) -> ${Rt(e)} { + return ${Rt(e)}(${t}[getIndexFromCoords${c}(${r}(${o.join(",")}), + ${l})${e===1?"":` / ${e}`}]); + } + `}function $ee(n,e,t,s){const r=n.name,i=r.charAt(0).toUpperCase()+r.slice(1),o="get"+i+"ByOutput",a=n.shape.length,l=e.length,c=zn(l);if(Wt(n.shape,e)&&s)return` + fn ${o}Index(globalIndex : i32) -> ${Rt(t)} { + return ${Rt(t)}(${r}[globalIndex]); + } + + fn ${o}Coords(coords : ${c}) -> ${Rt(t)} { + return ${Rt(t)}(${r}[${l>1?"getOutputIndexFromCoords(coords)":"coords"}${t===1?"":` / ${t}`}]); + } + `;const u=oa(n.shape,e),h=l-a;let d="";if(a===0)return` + fn ${o}Index(globalIndex : i32) -> ${Rt(t)}{ + return get${i}(); + } + + fn ${o}Coords(coords : ${c}) -> ${Rt(t)}{ + return get${i}(); + } + `;l<2&&u.length>=1?d="coords = 0;":d=u.map(m=>`coords.${Io(m+h)} = 0;`).join(` +`);let p="";if(l<2&&a>0)p="coords";else if(l>1){const m=zn(a),g=n.shape.map((v,b)=>`coords.${Io(b+h)}`).join(", ");p=`${m}(${g})`}else p="coords";const f=`uniforms.${r.charAt(0).toLowerCase()+r.slice(1)}Shape`,x=`${a}D`;return` + fn ${o}Index(globalIndex : i32) -> ${Rt(t)} { + var coords = getCoordsFromIndex(globalIndex); + ${d} + return ${Rt(t)}(${r}[getIndexFromCoords${x}(${p}, ${f})${t===1?"":` / ${t}`}]); + } + + fn ${o}Coords(coordsIn : ${c}) -> ${Rt(t)} { + var coords = coordsIn; + ${d} + return ${Rt(t)}(${r}[getIndexFromCoords${x}(${p}, ${f})${t===1?"":` / ${t}`}]); + } +`}function Dee(n,e,t,s){let r=Nee(n,t);return n.shape.length<=e.length&&(r+=$ee(n,e,t,s)),r}function Pee(n,e){const{x:t,y:s=[],z:r=[]}=e,i=n.length,o=t.length+s.length+r.length;if(o!==i)return"";if(t.length===i)return`fn getOutputCoords() -> ${zn(i)}{ + let globalIndex = getGlobalIndex(); + return getCoordsFromIndex(globalIndex); + } + `;let a="";const l=[t,s,r];for(let d=0;d ${u} { + ${a} +`;return c.length===0?h+=`return ${u}(0); }`:h+=`return ${u}(${c.join(",")}); }`,h}function Lee(n){let e="";switch(n){case 0:case 1:e+=` + fn getOutputIndexFromCoords(coords : i32) -> i32 { + return coords; + } + `;break;case 2:e+=` + fn getOutputIndexFromCoords(coords : vec2) -> i32 { + return dot(coords, vec2(uniforms.outShapeStrides, 1)); + } + `;break;case 3:e+=` + fn getOutputIndexFromCoords(coords : vec3) -> i32 { + return dot(coords, vec3(uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, 1)); + } + `;break;case 4:e+=` + fn getOutputIndexFromCoords(coords : vec4) -> i32 { + return dot(coords, vec4( + uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, uniforms.outShapeStrides.z, 1)); + } + `;break;case 5:e+=` + fn getOutputIndexFromCoords(coords : vec5) -> i32 { + return coords.x * uniforms.outShapeStrides.x + + coords.y * uniforms.outShapeStrides.y + + coords.z * uniforms.outShapeStrides.z + + coords.w * uniforms.outShapeStrides.w + + coords.u; + } + `;break;case 6:e+=` + fn getOutputIndexFromCoords(coords : vec6) -> i32 { + return coords.x * uniforms.outShapeStrides.x + + coords.y * uniforms.outShapeStrides.y + + coords.z * uniforms.outShapeStrides.z + + coords.w * uniforms.outShapeStrides.w + + coords.u * uniforms.outShapeStrides.u + + coords.v; + } + `;break;default:N(!1,()=>`Unsupported ${n}D shape`);break}return e}function uk(n){return n.dispatch[1]===1&&n.dispatch[2]===1}function Ya(n,e=1){if(n==="float32")return Rt(e,"f32");if(n==="int32"||n==="bool")return Rt(e,"i32");throw new Error(`type ${n} is not supported.`)}function Fee(n,e,t){const s=n.length,r=Ya(e,t);let i=`fn setOutputAtIndex(flatIndex : i32, value : ${Rt(t)}) { + result[flatIndex] = ${r}(value); + } + + fn setOutputAtIndexI32(flatIndex : i32, value : ${Rt(t,"i32")}) { + result[flatIndex] = ${r}(value); + } + `;if(s>=2){const o=["d0","d1","d2","d3","d4","d5"].slice(0,s),a=zn(s);i+=` + fn setOutputAtCoords(${o.map(l=>`${l} : i32`).join(", ")}, value : ${Rt(t)}) { + let flatIndex = getOutputIndexFromCoords(${a}(${o.join(", ")})); + setOutputAtIndex(flatIndex${t===1?"":` / ${t}`}, value); + } + fn setOutputAtCoordsI32(${o.map(l=>`${l} : i32`).join(", ")}, value : ${Rt(t,"i32")}) { + let flatIndex = getOutputIndexFromCoords(${a}(${o.join(", ")})); + setOutputAtIndexI32(flatIndex${t===1?"":` / ${t}`}, value); + } + `}return i}function Oee(n){const e=/(\w+)\s*:\s*vec(5|6)/g;n=n.replace(e,s=>"@align(16) "+s);const t=/vec(5|6)\s*,\s*(\w+)/g;return n=n.replace(t,(s,r,i)=>`vec${r}, @align(16) ${i}`),n}function Aw(n){return!(n.dispatchLayout.hasOwnProperty("y")&&n.dispatchLayout.y.length!==0||n.dispatchLayout.hasOwnProperty("z")&&n.dispatchLayout.z.length!==0)}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ll=n=>{let e=1;for(let t=0;te[a]))/(t[0]*s[0])),n.y?Math.ceil(ll(n.y.map(a=>e[a]))/(t[1]*s[1])):1,n.z?Math.ceil(ll(n.z.map(a=>e[a]))/(t[2]*s[2])):1];return[r,i,o]}function zee(n,e,t,s=!1){const r=[8,8,1],i=[4,4,1];return s||(n<=8&&(i[1]=1),e<=16&&t<=16&&(r[0]=4)),{workgroupSize:r,elementsPerThread:i}}function hk(n,e,t=!1){if(t)return[8,8,1];const s=ll(n.x.map(i=>e[i])),r=ll(n.y.map(i=>e[i]));return s<=4?[4,16,1]:r<=4?[16,4,1]:[16,16,1]}function dk(n,e,t=!1){if(t)return[4,4,1];const s=ll(n.x.map(i=>e[i])),r=ll(n.y.map(i=>e[i]));return s<=4?[1,2,1]:r<=4?[2,1,1]:[2,2,1]}function Xe(n){return{x:n.map((e,t)=>t)}}function Rw(n){if(n==="float32"||n==="int32"||n==="bool"||n==="string")return 4;if(n==="complex64")return 8;throw new Error(`Unknown dtype ${n}`)}function pk(){return!!(typeof globalThis<"u"&&globalThis.navigator&&globalThis.navigator.gpu)}function fk(n,e){Array.isArray(n)||(n=[n]),n.forEach(t=>{t!=null&&N(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the WebGPU backend.`)})}var $i;(function(n){n[n.MatMulReduceProgram=0]="MatMulReduceProgram",n[n.MatMulSplitKProgram=1]="MatMulSplitKProgram",n[n.MatMulSmallOutputSizeProgram=2]="MatMulSmallOutputSizeProgram",n[n.MatMulPackedProgram=3]="MatMulPackedProgram",n[n.MatMulMax=4]="MatMulMax"})($i||($i={}));/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Bee=oe().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),Uee=(n,e)=>{const t=n.limits.maxComputeWorkgroupsPerDimension,s=e.dispatchLayout,r=e.dispatch;if(r.every(o=>o<=t))return r;N(r[0]>t&&s.y===void 0&&s.z===void 0,()=>"Dispatch size exceeds WebGPU limits in Y or Z dimension.");let i=Math.ceil(Math.sqrt(r[0]));return i>t?(i=Math.ceil(Math.cbrt(r[0])),N(i<=t,()=>"Total dispatch size exceeds WebGPU maximum."),[i,i,i]):[i,i,1]};class Qm extends b0{nextDataId(){return Qm.nextDataId++}constructor(e,t){if(super(),this.commandQueueOwnedIds=new WeakSet,this.dispatchCountInPass=0,this.disposed=!1,this.downloadWaitMs=0,this.tensorDataPendingDisposal=[],this.queryResolveBuffer=null,this.querySet=null,this.querySetCount=2,this.stagingPendingDisposal=[],this.uniformPendingDisposal=[],this.uploadWaitMs=0,this.hasReadSyncWarned=!1,this.hasTimestampQueryWarned=!1,!pk())throw new Error("WebGPU is not supported on this device");this.pipelineCache={},this.device=e,this.queue=e.queue,this.commandEncoder=null,this.computePassEncoder=null,this.adapterInfo=new Cee(t),this.supportTimestampQuery=this.device.features.has("timestamp-query"),this.thresholdToIncreaseWorkgroups=this.adapterInfo.intelGPUGeneration>=12?16:8,this.bufferManager=new _ee(this.device),this.textureManager=new Tee(this.device),this.tensorMap=new t2(this,Tr()),oe().getBool("WEBGPU_USE_PROFILE_TOOL")&&(this.dummyCanvas=document.createElement("canvas"),this.dummyCanvas.width=1,this.dummyCanvas.height=1,this.dummyContext=this.dummyCanvas.getContext("webgpu"),this.dummyContext.configure({device:e,format:"bgra8unorm"}),document.body.appendChild(this.dummyCanvas))}floatPrecision(){return 32}disposeData(e,t=!1){if(!this.tensorMap.has(e))return!0;const s=this.tensorMap.get(e);return t?s.refCount=0:s.refCount--,s.refCount>0?!1:(s.complexTensorInfos!=null&&(this.disposeData(s.complexTensorInfos.real.dataId),this.disposeData(s.complexTensorInfos.imag.dataId)),this.commandQueueOwnedIds.has(e)?(this.tensorDataPendingDisposal.push(e),!0):(this.releaseResource(e),this.tensorMap.delete(e),!0))}memory(){return{numBytesInGPU:this.bufferManager.numBytesUsed,numBytesAllocatedInGPU:this.bufferManager.numBytesAllocated,unreliable:!1}}releaseResource(e){const t=this.tensorMap.get(e);if(!(!t||!t.resource)){if(t.external){t.resource=null;return}t.resource instanceof GPUBuffer?this.bufferManager.releaseBuffer(t.resource):t.resource instanceof GPUTexture&&this.textureManager.releaseTexture(t.resource),t.resource=null}}refCount(e){return this.tensorMap.has(e)?this.tensorMap.get(e).refCount:0}incRef(e){const t=this.tensorMap.get(e);t.refCount++}decRef(e){if(this.tensorMap.has(e)){const t=this.tensorMap.get(e);t.refCount--}}write(e,t,s){if(s==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const r={id:this.nextDataId()};return this.tensorMap.set(r,{dtype:s,shape:t,values:e,refCount:1}),r}move(e,t,s,r,i){if(r==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.tensorMap.set(e,{dtype:r,shape:s,values:t,refCount:i})}submitQueue(){this.queue.submit([this.commandEncoder.finish()]),this.commandEncoder=null,this.dispatchCountInPass=0,this.commandQueueOwnedIds=new WeakSet,this.tensorDataPendingDisposal.forEach(e=>{this.releaseResource(e),this.tensorMap.delete(e)}),this.uniformPendingDisposal.forEach(e=>this.bufferManager.releaseBuffer(e)),this.stagingPendingDisposal.forEach(e=>this.bufferManager.releaseBuffer(e,!1)),this.tensorDataPendingDisposal=[],this.uniformPendingDisposal=[],this.stagingPendingDisposal=[]}ensureCommandEncoderReady(){this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder())}endComputePassEncoder(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}async checkCompileCompletionAsync(){let e;try{e=await Promise.all(Object.values(this.pipelineCache))}catch(t){throw new Error(t.message)}Object.keys(this.pipelineCache).map((t,s)=>{this.pipelineCache[t]=e[s]})}async getBufferData(e){if(oe().getBool("WEBGPU_ENGINE_COMPILE_ONLY"))return console.warn("The data may be invalid since WEBGPU_ENGINE_COMPILE_ONLY is true, this can only be called when WEBGPU_ENGINE_COMPILE_ONLY is false"),null;const t=e.size,s=this.bufferManager.acquireBuffer(t,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ);this.ensureCommandEncoderReady(),this.endComputePassEncoder(),this.commandEncoder.copyBufferToBuffer(e,0,s,0,t),this.submitQueue(),await s.mapAsync(GPUMapMode.READ);const r=s.getMappedRange().slice(0);return s.unmap(),s!=null&&this.bufferManager.releaseBuffer(s),oe().getBool("WEBGPU_USE_PROFILE_TOOL")&&(N(this.dummyContext!==void 0,()=>"Fail to get context for profiling tool"),this.dummyContext.getCurrentTexture()),r}convertAndCacheOnCPU(e,t){const s=this.tensorMap.get(e);return s.values=t,s.values}readSync(e){const t=this.tensorMap.get(e),{values:s,complexTensorInfos:r}=t;if(s!=null||t.dtype==="string")return s;if(t.dtype==="complex64"){const x=this.readSync(r.real.dataId),m=this.readSync(r.imag.dataId),g=Sf(_i(x,m).buffer,"float32");return this.convertAndCacheOnCPU(e,g),g}this.hasReadSyncWarned||(this.hasReadSyncWarned=!0,console.warn("The performance of synchronously reading data from GPU to CPU is poor on the webgpu backend, please use asynchronous APIs instead."));const i=["opaque","premultiplied"],o=t.resource,a=o.size;N(a%4===0,()=>"Because there is 4 bytes for one pixel, buffer size must be multiple of 4.");const l=a/4,c=new ArrayBuffer(a),u=256,h=256,d=i.map(x=>new OffscreenCanvas(u,h)),p=new OffscreenCanvas(u,h);this.endComputePassEncoder(),d.map((x,m)=>{const g=x.getContext("webgpu");return g.configure({device:this.device,format:"bgra8unorm",usage:GPUTextureUsage.COPY_DST,alphaMode:i[m]}),g.getCurrentTexture()}).map((x,m)=>{const g=u*4,v=(E,R,_)=>{this.ensureCommandEncoderReady(),this.commandEncoder.copyBufferToTexture({buffer:o,bytesPerRow:g,offset:_},{texture:x},{width:E,height:R}),this.submitQueue();const k=p.getContext("2d",{willReadFrequently:!0});k.clearRect(0,0,E,R),k.drawImage(d[m],0,0);const F=k.getImageData(0,0,E,R).data,B=i[m],M=new Uint8ClampedArray(c,_,E*R*4);for(let P=0;P0&&(v(y,w,C),C+=w*(u*4)),y=T%u,y>0&&v(y,1,C)});const f=Sf(c,t.dtype);return this.convertAndCacheOnCPU(e,f),f}async read(e){if(!this.tensorMap.has(e))throw new Error(`Tensor ${e} was not registered!`);const t=this.tensorMap.get(e),{values:s}=t;if(s!=null)return s;let r;if(t.dtype==="complex64"){const i=await Promise.all([this.read(t.complexTensorInfos.real.dataId),this.read(t.complexTensorInfos.imag.dataId)]),o=i[0],a=i[1];r=_i(o,a)}else{const i=await this.getBufferData(t.resource);r=Sf(i,t.dtype)}return this.convertAndCacheOnCPU(e,r),r}copyBuffer(e){const t=e.size,s=e.usage,r=this.bufferManager.acquireBuffer(t,s);return this.ensureCommandEncoderReady(),this.endComputePassEncoder(),this.commandEncoder.copyBufferToBuffer(e,0,r,0,t),this.submitQueue(),r}createTensorFromGPUData(e,t,s){let r=e.buffer;if(s==="complex64")throw new Error("Cannot write to a complex64 dtype. ");const i={id:this.nextDataId()};this.tensorMap.set(i,{dtype:s,shape:t,values:null,refCount:1,external:e.zeroCopy});const o=this.tensorMap.get(i),a=Rw(o.dtype)*re(o.shape);if(e.buffer.sizeCi(r));return Tt(e.shape,e.dtype,s)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return Tt(e.shape,e.dtype,t)}async time(e){!this.supportTimestampQuery&&!this.hasTimestampQueryWarned&&(console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --enable-dawn-features=allow_unsafe_apis to try it again. Otherwise, zero will be shown for the kernel time when profiling mode is enabled."),this.hasTimestampQueryWarned=!0);const t=this.activeTimers,s=[];let r=!1;this.programTimersStack==null?(this.programTimersStack=s,r=!0):this.activeTimers.push(s),this.activeTimers=s,e();const i=ko(this.activeTimers.map(c=>c.query)).filter(c=>c!=null),o=ko(this.activeTimers.map(c=>c.name)).filter(c=>c!=null);this.activeTimers=t,r&&(this.programTimersStack=null);const a={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},l=await Promise.all(i);return a.kernelMs=qS(l),a.getExtraProfileInfo=()=>l.map((c,u)=>({name:o[u],ms:c})).map(c=>`${c.name}: ${c.ms}`).join(", "),this.uploadWaitMs=0,this.downloadWaitMs=0,a}makeTensorInfo(e,t,s){return t==="string"&&s!=null&&s.length>0&&Kc(s[0])&&(s=s.map(i=>_o(i))),{dataId:this.write(s,e,t),shape:e,dtype:t}}tensorToBinding(e){if(!e)return null;const s=this.tensorMap.get(e.dataId).resource;return s instanceof GPUBuffer?{buffer:s}:s instanceof GPUTexture?s.createView():s}uploadToGPU(e){const t=this.tensorMap.get(e);if(t.resource!=null)return;const s=Rw(t.dtype)*re(t.shape);let r;const i=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;if(t.values){if(r=this.bufferManager.acquireBuffer(s,i,!0),r.mapState==="unmapped"){const o=this.bufferManager.acquireBuffer(s,GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,!0,!1),a=o.getMappedRange();t.dtype==="int32"||t.dtype==="bool"?new Int32Array(a).set(t.values):new Float32Array(a).set(t.values),o.unmap(),this.ensureCommandEncoderReady(),this.endComputePassEncoder(),this.commandEncoder.copyBufferToBuffer(o,0,r,0,s),this.stagingPendingDisposal.push(o)}else{const o=r.getMappedRange();t.dtype==="int32"||t.dtype==="bool"?new Int32Array(o).set(t.values):new Float32Array(o).set(t.values),r.unmap()}t.values=null}else r=this.bufferManager.acquireBuffer(s,i);t.resource=r}makeUniforms(e){let t=0,s=0;const r=[];let i=1;e.forEach(l=>{l.data.length===0&&(l.data=[1]);let c;switch(l.data.length){case 1:c=4;break;case 2:c=8;break;case 3:c=16;break;case 4:c=16;break;case 5:c=16;break;case 6:c=16;break;default:N(!1,()=>`Unsupported ${l.data.length}D shape`)}(s===5||s===6)&&(c=16),c>i&&(i=c),t=Math.ceil(t/c)*c,s=l.data.length,r.push(t),t+=l.data.length*4}),t=Math.ceil(t/i)*i;const o=new ArrayBuffer(t);e.forEach((l,c)=>{const u=r[c];l.type==="int32"?new Int32Array(o,u,l.data.length).set(l.data):l.type==="uint32"?new Uint32Array(o,u,l.data.length).set(l.data):new Float32Array(o,u,l.data.length).set(l.data)});const a=this.bufferManager.acquireBuffer(t,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);return this.queue.writeBuffer(a,0,o,0,t),this.uniformPendingDisposal.push(a),{offset:0,size:t,buffer:a}}runWebGPUProgram(e,t,s,r,i){if(i||(i=this.makeTensorInfo(e.outputShape,s)),re(i.shape)===0)return this.tensorMap.get(i.dataId).values=hs(i.dtype,0),i;this.uploadToGPU(i.dataId),e.dispatch=Uee(this.device,e);const o=t.map((l,c)=>{if(l.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");return this.uploadToGPU(l.dataId),{dtype:this.tensorMap.get(l.dataId).dtype,shape:l.shape,name:e.variableNames[c]}});e.shaderKey=Ree(e,o,i);const a=oe().getBool("WEBGPU_ENGINE_COMPILE_ONLY");return e.shaderKey in this.pipelineCache||(this.pipelineCache[e.shaderKey]=Eee(this.device,e,o,i,a)),e.pipeline=this.pipelineCache[e.shaderKey],a||this.recordAndSubmit(e,i,t,r),i}recordAndSubmit(e,t,s,r){if(e.pipeline instanceof Promise)throw new Error("Please call checkCompileCompletionAsync to ensure parallel compilation is done!");let i=[],o=[];const a="int32";if(e.pixelsOpType==null){i.push({type:"float32",data:[NaN]},{type:"float32",data:[1/0]}),o=s.concat(t).map(p=>p.shape);const d="int32";o.map(p=>{i.push({type:d,data:p});const f=it(p);i.push({type:d,data:f})})}else{const d=it(t.shape);i.push({type:a,data:d})}if(e.size){const d=re(e.outputShape);i.push({type:a,data:[e.outputComponent?d/e.outputComponent:d]})}r&&(i=[...i,...r]);const l=[this.tensorToBinding(t),...s.map(d=>this.tensorToBinding(d)),this.makeUniforms(i)];s.forEach(d=>{this.commandQueueOwnedIds.add(d.dataId)}),this.commandQueueOwnedIds.add(t.dataId);const c=this.device.createBindGroup({layout:e.pipeline.getBindGroupLayout(0),entries:l.map((d,p)=>({binding:p,resource:d}))}),u=this.activeTimers!=null;this.ensureCommandEncoderReady();const h={};u&&this.supportTimestampQuery?(this.endComputePassEncoder(),this.querySet==null&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.querySetCount})),h.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:0,endOfPassWriteIndex:1},this.computePassEncoder=this.commandEncoder.beginComputePass(h)):this.computePassEncoder||(this.computePassEncoder=this.commandEncoder.beginComputePass(h)),this.computePassEncoder.setPipeline(e.pipeline),this.computePassEncoder.setBindGroup(0,c),this.computePassEncoder.dispatchWorkgroups(e.dispatch[0],e.dispatch[1],e.dispatch[2]),this.dispatchCountInPass++,(u||oe().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE")<=this.dispatchCountInPass||e.pixelsOpType===Bc.DRAW)&&(this.endComputePassEncoder(),u?this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime()}):this.submitQueue())}async getQueryTime(){if(!this.supportTimestampQuery)return 0;this.queryResolveBuffer==null&&(this.queryResolveBuffer=this.bufferManager.acquireBuffer(this.querySetCount*8,GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST|GPUBufferUsage.QUERY_RESOLVE)),this.commandEncoder.resolveQuerySet(this.querySet,0,this.querySetCount,this.queryResolveBuffer,0);const e=this.bufferManager.acquireBuffer(this.querySetCount*8,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST);this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.querySetCount*8),this.submitQueue(),await e.mapAsync(GPUMapMode.READ);const t=new BigUint64Array(e.getMappedRange()),s=Number(t[1]-t[0])/1e6;return e.unmap(),this.bufferManager.releaseBuffer(e),s}shouldExecuteOnCPU(e,t=Bee){return oe().getBool("WEBGPU_CPU_FORWARD")&&e.every(s=>this.tensorMap.get(s.dataId).resource==null&&re(s.shape){const n={powerPreference:oe().get("WEBGPU_USE_LOW_POWER_GPU")?"low-power":"high-performance"},e=await navigator.gpu.requestAdapter(n),t={},s=[];e.features.has("timestamp-query")&&s.push("timestamp-query"),e.features.has("bgra8unorm-storage")&&s.push(["bgra8unorm-storage"]),t.requiredFeatures=s;const r=e.limits;t.requiredLimits={maxComputeWorkgroupStorageSize:r.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.maxStorageBufferBindingSize,maxBufferSize:r.maxBufferSize,maxComputeWorkgroupSizeX:r.maxComputeWorkgroupSizeX,maxComputeInvocationsPerWorkgroup:r.maxComputeInvocationsPerWorkgroup};const i=await e.requestDevice(t),o="info"in e?e.info:"requestAdapterInfo"in e?await e.requestAdapterInfo():void 0;return new Qm(i,o)},3);/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var bt;(function(n){n[n.ADD=0]="ADD",n[n.ATAN2=1]="ATAN2",n[n.COMPLEX_MULTIPLY_IMAG=2]="COMPLEX_MULTIPLY_IMAG",n[n.COMPLEX_MULTIPLY_REAL=3]="COMPLEX_MULTIPLY_REAL",n[n.DIV=4]="DIV",n[n.ELU_DER=5]="ELU_DER",n[n.EQUAL=6]="EQUAL",n[n.FLOOR_DIV=7]="FLOOR_DIV",n[n.GREATER=8]="GREATER",n[n.GREATER_EQUAL=9]="GREATER_EQUAL",n[n.LESS=10]="LESS",n[n.LESS_EQUAL=11]="LESS_EQUAL",n[n.LOGICAL_AND=12]="LOGICAL_AND",n[n.LOGICAL_OR=13]="LOGICAL_OR",n[n.MAX=14]="MAX",n[n.MIN=15]="MIN",n[n.MOD=16]="MOD",n[n.MUL=17]="MUL",n[n.NOT_EQUAL=18]="NOT_EQUAL",n[n.POW=19]="POW",n[n.PRELU=20]="PRELU",n[n.SQUARED_DIFFERENCE=21]="SQUARED_DIFFERENCE",n[n.SUB=22]="SUB"})(bt||(bt={}));const Vee="let resultTemp = a + b;",Wee="let resultTemp = atan2(a, b);",Gee="let resultTemp = areal * breal - aimag * bimag;",Hee="let resultTemp = areal * bimag + aimag * breal;",qee="let resultTemp = a / b;",Xee="let resultTemp = select(a * (b + 1.0), a, b >= b - b);",Kee=` + let zero = sign(a) * 0 + 0; + let one = sign(b) * 0 + 1; + let resultTemp = select(zero, one, a == b); +`,jee=` + let remainder = + select(a % b, round(a % b), (round(a) == a) & (round(b) == b)); + let quotient = (a - remainder) / b; + let resultTemp = + round(select(quotient, quotient - 1, sign(remainder) == -sign(b))); +`,Yee=` + let zero = sign(a) * 0 + 0; + let one = sign(b) * 0 + 1; + let resultTemp = select(zero, one, a > b); +`,Zee=` + let zero = sign(a) * 0 + 0; + let one = sign(b) * 0 + 1; + let resultTemp = select(zero, one, a >= b); +`,Jee=` + let zero = sign(a) * 0 + 0; + let one = sign(b) * 0 + 1; + let resultTemp = select(zero, one, a < b); +`,Qee=` + let zero = sign(a) * 0 + 0; + let one = sign(b) * 0 + 1; + let resultTemp = select(zero, one, a <= b); +`,ete="return f32(a >= 1.0 && b >= 1.0);",tte=`return (vec4(a >= vec4(1.0)) * + vec4(b >= vec4(1.0)));`,nte="return f32(a >= 1.0 || b >= 1.0);",ste=`return min(vec4(a >= vec4(1.0)) + + vec4(b >= vec4(1.0)), vec4(1.0));`,rte="let resultTemp = max(a, b);",ite="let resultTemp = min(a, b);",ote=` + let isNaN = b == 0.; + var resultTemp = a % b; + resultTemp = select((resultTemp + b) % b, resultTemp, + (a < 0. && b < 0.) || (a >= 0. && b > 0.)); +`,ate=` + let isNaN = !vec4(b); + var resultTemp = vec4(a % b); + if (!((a[0] < 0. && b[0] < 0.) || (a[0] >= 0. && b[0] > 0.))) { + resultTemp[0] = (resultTemp[0] + b[0]) % b[0]; + } + if (!((a[1] < 0. && b[1] < 0.) || (a[1] >= 0. && b[1] > 0.))) { + resultTemp[1] = (resultTemp[1] + b[1]) % b[1]; + } + if (!((a[2] < 0. && b[2] < 0.) || (a[2] >= 0. && b[2] > 0.))) { + resultTemp[2] = (resultTemp[2] + b[2]) % b[2]; + } + if (!((a[3] < 0. && b[3] < 0.) || (a[3] >= 0. && b[3] > 0.))) { + resultTemp[3] = (resultTemp[3] + b[3]) % b[3]; + } +`,lte="let resultTemp = a * b;",cte=` + var resultTemp = f32(a != b); + let valueForNaN = 1.0; +`,ute=` + var resultTemp = vec4(a != b); + let valueForNaN = 1.0; +`,hte=` + let isNaN = a < 0.0 && floor(b) < b; + if (b == 0.0) { + return 1.0; + } + var resultTemp = select(sign(a) * pow(abs(a), b), pow(abs(a), b), + round(abs(b) % 2.0) != 1.0); +`,dte=` + let isModRound1Bool = vec4(round(abs(b) % vec4(2.0))) == vec4(1); + let isModRound1 = vec4(isModRound1Bool); + let multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1); + var resultTemp = multiplier * pow(abs(a), b); + + // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS + let isExpZero = b == vec4(0.0); + if (isExpZero.r) { + resultTemp.r = 1.0; + } + if (isExpZero.g) { + resultTemp.g = 1.0; + } + if (isExpZero.b) { + resultTemp.b = 1.0; + } + if (isExpZero.a) { + resultTemp.a = 1.0; + } + let isNaN = (a < vec4(0.0)) & (floor(b) < b); +`,pte="if (a < 0.0) { return b * a; } return a;",fte=` + let aLessThanZero = vec4(a < vec4(0.0)); + return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); +`,mte="let resultTemp = (a - b) * (a - b);",gte="let resultTemp = a - b;";function sb(n,e){let t;do{switch(n){case bt.ATAN2:t=Wee;break;case bt.MAX:t=rte;break;case bt.MIN:t=ite;break;case bt.MOD:t=e?ate:ote;break;case bt.NOT_EQUAL:t=e?ute:cte;break;case bt.POW:t=e?dte:hte;break;default:continue}let s,r,i;return e?(s="isnanVec4",r="vec4",i="vec4"):(s="isnan",r="f32",i="bool"),` + let aIsNaN = ${s}(a); + let aPostLegalization = select(a, ${r}(42), aIsNaN); + let bIsNaN = ${s}(b); + let bPostLegalization = select(b, ${r}(42), bIsNaN); + let isNaN = false; + let valueForNaN = uniforms.NAN; + { + let a = aPostLegalization; + let b = bPostLegalization; + ${t} + return select( + resultTemp, ${r}(valueForNaN), + ${i}(isNaN) | aIsNaN | bIsNaN); + } + `}while(!1);switch(n){case bt.ADD:t=Vee;break;case bt.COMPLEX_MULTIPLY_IMAG:t=Hee;break;case bt.COMPLEX_MULTIPLY_REAL:t=Gee;break;case bt.DIV:t=qee;break;case bt.ELU_DER:t=Xee;break;case bt.EQUAL:t=Kee;break;case bt.FLOOR_DIV:t=jee;break;case bt.GREATER:t=Yee;break;case bt.GREATER_EQUAL:t=Zee;break;case bt.LESS:t=Jee;break;case bt.LESS_EQUAL:t=Qee;break;case bt.LOGICAL_AND:return e?tte:ete;case bt.LOGICAL_OR:return e?ste:nte;case bt.MUL:t=lte;break;case bt.PRELU:return e?fte:pte;case bt.SQUARED_DIFFERENCE:t=mte;break;case bt.SUB:t=gte;break}return` + ${t} + return resultTemp; + `}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Me;(function(n){n[n.ABS=0]="ABS",n[n.ACOS=1]="ACOS",n[n.ACOSH=2]="ACOSH",n[n.ASIN=3]="ASIN",n[n.ASINH=4]="ASINH",n[n.ATAN=5]="ATAN",n[n.ATANH=6]="ATANH",n[n.CEIL=7]="CEIL",n[n.COS=8]="COS",n[n.COSH=9]="COSH",n[n.ELU=10]="ELU",n[n.ERF=11]="ERF",n[n.EXP=12]="EXP",n[n.EXPM1=13]="EXPM1",n[n.FLOOR=14]="FLOOR",n[n.IS_FINITE=15]="IS_FINITE",n[n.IS_INF=16]="IS_INF",n[n.IS_NAN=17]="IS_NAN",n[n.LINEAR=18]="LINEAR",n[n.LOG=19]="LOG",n[n.LOG1P=20]="LOG1P",n[n.LOGICAL_NOT=21]="LOGICAL_NOT",n[n.NEG=22]="NEG",n[n.RELU=23]="RELU",n[n.RELU6=24]="RELU6",n[n.LEAKYRELU=25]="LEAKYRELU",n[n.RECIPROCAL=26]="RECIPROCAL",n[n.ROUND=27]="ROUND",n[n.RSQRT=28]="RSQRT",n[n.SELU=29]="SELU",n[n.SIGMOID=30]="SIGMOID",n[n.SIGN=31]="SIGN",n[n.SIN=32]="SIN",n[n.SINH=33]="SINH",n[n.SOFTPLUS=34]="SOFTPLUS",n[n.SQRT=35]="SQRT",n[n.SQUARE=36]="SQUARE",n[n.STEP=37]="STEP",n[n.TAN=38]="TAN",n[n.TANH=39]="TANH",n[n.TO_INT=40]="TO_INT"})(Me||(Me={}));const xte="return abs(a);",vte=` + if (abs(a) > 1.) { + return uniforms.NAN; + } + return acos(a); +`,bte=` + if (a < 1.) { + return uniforms.NAN; + } + return acosh(a); +`,yte=` + if (abs(a) > 1.) { + return uniforms.NAN; + } + return asin(a); +`,wte="return asinh(a);",Ste=` + if (isnan(a)) { + return uniforms.NAN; + } + return atan(a); +`,Cte=` + if (abs(a) > 1.) { + return uniforms.NAN; + } + if (a == 1.) { + return uniforms.INFINITY; + } + if (a == -1.) { + return -uniforms.INFINITY; + } + return atanh(a); +`,_te="return ceil(a);",Tte="return cos(a);",Ite=` + let e2x = exp(-a); + return (e2x + 1.0 / e2x) / 2.0; +`,Ete="return exp(a) - 1.0;",kte="if (a >= 0.0) { return a; } return (exp(a) - 1.0);",Ate=` + var resFloat = exp(a) - vec4(1.0); + if (a.r >= 0.0) { + resFloat.r = a.r; + } + if (a.g >= 0.0) { + resFloat.g = a.g; + } + if (a.b >= 0.0) { + resFloat.b = a.b; + } + if (a.a >= 0.0) { + resFloat.a = a.a; + } + return resFloat; +`,Rte=` + // Error function is calculated approximately with elementary function. + // See "Handbook of Mathematical Functions with Formulas, + // Graphs, and Mathematical Tables", Abramowitz and Stegun. + let p = ${_m}; + let a1 = ${Tm}; + let a2 = ${Im}; + let a3 = ${Em}; + let a4 = ${km}; + let a5 = ${Am}; + + let sign = sign(a); + let absA = abs(a); + let t = 1.0 / (1.0 + p * absA); + return sign * (1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * exp(-absA * absA)); +`,Mte="return exp(a);",Nte="return floor(a);",$te="return f32(!isnan(a) && !isinf(a));",Dte="return f32(isinf(a));",Pte="return f32(isnan(a));",Lte="return a;",Fte=`if (a < 0.0) { return uniforms.NAN; } + return log(a);`,Ote=` + if (isnan(a)) { return a; } + return log(1.0 + a); +`,zte="return f32(!(a >= 1.0));",Bte="return -a;",Ute="if (a < 0.0) { return uniforms.alpha * a; } return a;",Vte=` + let aLessThanZero = vec4(a < vec4(0.0)); + return (aLessThanZero * (uniforms.alpha * a)) + ((vec4(1.0) - aLessThanZero) * a); +`,Wte="return 1.0 / a;",Gte="return select(a, 0.0, a < 0.0);",Hte="return clamp(a, 0.0, 6.0);",qte="return clamp(a, vec4(0.0, 0.0, 0.0, 0.0), vec4(6.0, 6.0, 6.0, 6.0));",Xte=` + return select(a, vec4(0.0), a < vec4(0.0)); +`,Kte="return round(a);",jte="return inverseSqrt(a);",Yte=` + if (a >= 0.0) { + return ${op} * a; + } else { + return ${ip} * (exp(a) - 1.0); + } +`,Zte="return 1.0 / (1.0 + exp(-1.0 * a));",Jte="return sign(a);",Qte="return sin(a);",ene=` + let e2x = exp(a); + return (e2x - 1.0 / e2x) / 2.0; +`,tne=` + let epsilon = 1.1920928955078125e-7; + let threshold = log(epsilon) + 2.0; + + let too_large = a > -threshold; + let too_small = a < threshold; + let exp_a = exp(a); + + if (too_large) { + return a; + } else if (too_small) { + return exp_a; + } else { + return log(exp_a + 1.0); + } +`,nne="return sqrt(a);",sne="return a * a;",rne=` + if (isnan(a)) { + return a; + } + + return select(uniforms.stepAlpha, 1.0, a > 0.0); +`,ine="return tan(a);",one=` + let e2x = exp(-2.0 * abs(a)); + return sign(a) * (1.0 - e2x) / (1.0 + e2x); +`,ane="return f32(i32((a)));";function Ga(n,e){switch(n){case Me.ABS:return xte;case Me.ACOS:return vte;case Me.ACOSH:return bte;case Me.ASIN:return yte;case Me.ASINH:return wte;case Me.ATAN:return Ste;case Me.ATANH:return Cte;case Me.COS:return Tte;case Me.COSH:return Ite;case Me.CEIL:return _te;case Me.ELU:return e?Ate:kte;case Me.ERF:return Rte;case Me.EXP:return Mte;case Me.EXPM1:return Ete;case Me.FLOOR:return Nte;case Me.IS_FINITE:return $te;case Me.IS_INF:return Dte;case Me.IS_NAN:return Pte;case Me.LINEAR:return Lte;case Me.LOG:return Fte;case Me.LOG1P:return Ote;case Me.LOGICAL_NOT:return zte;case Me.NEG:return Bte;case Me.LEAKYRELU:return e?Vte:Ute;case Me.RECIPROCAL:return Wte;case Me.RELU:return e?Xte:Gte;case Me.RELU6:return e?qte:Hte;case Me.ROUND:return Kte;case Me.RSQRT:return jte;case Me.SELU:return Yte;case Me.SIGMOID:return Zte;case Me.SIGN:return Jte;case Me.SIN:return Qte;case Me.SINH:return ene;case Me.SOFTPLUS:return tne;case Me.SQRT:return nne;case Me.SQUARE:return sne;case Me.STEP:return rne;case Me.TAN:return ine;case Me.TANH:return one;case Me.TO_INT:return ane;default:throw new Error(`BinaryType ${n} is not implemented!`)}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Do(n,e=!1,t=!1,s=3){if(n===null)return"";let r="";if(n==="linear")r=Ga(Me.LINEAR);else if(n==="relu")r=Ga(Me.RELU,t);else if(n==="elu")r=Ga(Me.ELU,t);else if(n==="relu6")r=Ga(Me.RELU6,t);else if(n==="prelu")r=sb(bt.PRELU,t);else if(n==="sigmoid")r=Ga(Me.SIGMOID,t);else if(n==="leakyrelu")r=Ga(Me.LEAKYRELU,t);else throw new Error(`Activation ${n} has not been implemented for the WebGPU backend.`);const o=Rt(t?4:1);let a="";return e?a=` + fn activation(a : ${o}, coords : vec${s}) -> ${o} { + let b = getPreluActivationWeightsByOutputCoords(coords); + ${r} + }`:a=` + fn activation(a : ${o}, coords : vec${s}) -> ${o} { + ${r} + }`,a}function Wl(n,e){return` + ${n?"value = value + getBiasByOutputCoords(coords);":""} + ${e?"value = activation(value, coords);":""} + `}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mk(n,e,t=!1,s=!1,r=!1,i=1){N(n&&i===1||!n,()=>`transposeA ${n} is not compatible with component size ${i}`);const o=` + ${n?"value = getA(batch, col, row);":"value = getA(batch, row, col);"} + + `,a=e?"value = getB(batch, col, row);":"value = getB(batch, row, col);";return` + fn mm_readA(batch: i32, row: i32, col: i32) -> ${Rt(i)} { + var value = ${Rt(i)}(0.0); + ${t&&r?o:` + ${n?"if(row < uniforms.dimAOuter && col < uniforms.dimInner)":"if(row < uniforms.aShape[1] && col < uniforms.aShape[2])"} + { + ${o} + } + `} + return value; + } + + fn mm_readB(batch: i32, row: i32, col: i32) -> ${Rt(i)} { + var value = ${Rt(i)}(0.0); + ${a} + return value; + } + `}function rb(n,e,t,s,r=!1,i=!1,o=!1,a=1){return` + ${mk(t,s,r,i,o,a)} + fn mm_write(batch: i32, row: i32, col: i32, valueIn: ${Rt(a)}) { + ${r&&i?"":"if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)"} + { + var value = valueIn; + let coords = vec3(batch, row, col); + ${Wl(n,e)} + setOutputAtCoords(coords[0], coords[1], coords[2], value); + } + } + `}const lne=(n,e)=>n?` + mm_Asub[inputRow][inputCol] = mm_readA(batchA, + kStart + inputRow, + globalRowStart + inputCol * ${e}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batchA, + globalRow + innerRow, + kStart + inputCol * ${e}); + `,cne=(n,e,t,s)=>{if(n)return` + for (var k = 0; k < ${s}; k++) { + let BCached0 = mm_Bsub[k][tileCol]; + let ACached0 = mm_Asub[k][localRow]; + for (var i = 0; i < ${t}; i++) { + acc[i] = fma(BCached0, vec4(ACached0[i]), acc[i]); + } + }`;{let r="",i="";for(let o=0;o(ACached[${o}]), acc[i]);`;return` + for (var k = 0; k < ${s/e}; k++) { + ${r} + for (var i = 0; i < ${t}; i++) { + let ACached = mm_Asub[tileRow + i][k]; + ${i} + } + }`}};function eg(n,e,t=!1,s=32,r=!1,i=32,o=!1){const a=e[1]*n[1],l=e[0]*n[0],c=t?a:s,u=t?s:a,h=c/e[0],d=s/e[1],p=n[1],f=n[0];return N((t&&h===4&&n[1]===4||!t&&(h===3||h===4))&&c%e[0]===0&&s%e[1]===0&&n[0]===4,()=>`If transposeA ${t} is true, innerElementSize ${h} and workPerThread[1] ${n[1]} must be 4. + Otherwise, innerElementSize ${h} must be 3 or 4. + tileAWidth ${c} must be divisible by workgroupSize[0]${e[0]}. tileInner ${s} must be divisible by workgroupSize[1] ${e[1]}. colPerThread ${n[0]} must be 4.`),` + var mm_Asub : array, ${c/h}>, ${u}>; + var mm_Bsub : array, ${l/n[0]}>, ${s}>; + + ${De()} { + let localRow = i32(localId.y); + let tileRow = localRow * ${p}; + let tileCol = i32(localId.x); + + let globalRow = i32(globalId.y) * ${p}; + let globalCol = i32(globalId.x) * ${f}; + let batch = ${r?"0":"i32(globalId.z)"}; + let batchA = ${r||!o?"batch":"batch % uniforms.aShape[0]"}; + let batchB = ${r||!o?"batch":"batch % uniforms.bShape[0]"}; + let globalRowStart = i32(workgroupId.y) * ${a}; + + let numTiles = ${r?`${Math.ceil(i/s)}`:`(uniforms.dimInner - 1) / ${s} + 1`}; + var kStart = ${r?`i32(globalId.z) * ${i}`:"0"}; + + var acc: array, ${p}>; + + // Loop over shared dimension. + let tileRowB = localRow * ${d}; + for (var t = 0; t < numTiles; t++) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${p}; innerRow++) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${lne(t,h)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${d}; innerRow++) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batchB, kStart + inputRow, globalCol); + } + kStart = kStart + ${s}; + workgroupBarrier(); + + // Compute acc values for a single thread. + ${cne(t,h,p,s)} + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < ${p}; innerRow++) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } + }`}const Mw=n=>n?` + mm_Asub[inputRow][inputCol] = mm_readA(batchA, + kStart + inputRow, + globalRowStart + inputCol); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batchA, + globalRowStart + inputRow, + kStart + inputCol); + `,une=n=>n?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];";function tg(n,e,t=!1,s=32,r=!1,i=32,o=!1,a=!1){const l=n[1]*e[1],c=n[0]*e[0],u=t?l:s,h=t?s:l;N(h%e[1]===0&&u%e[0]===0&&s%e[1]===0,()=>`tileAHight ${h} must be divisible by workgroupSize[1]${e[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${e[0]}, tileInner ${s} must be divisible by workgroupSize[1]${e[1]}`);const d=h/e[1],p=u/e[0],f=s/e[1],x=n[1],m=n[0],g=o?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${l}; + let globalColStart = i32(workgroupId.x) * ${c}; + + // Loop over shared dimension. + for (var t = 0; t < numTiles; t++) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${h}; inputRow = inputRow + ${e[1]}) { + for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${e[0]}) { + ${Mw(t)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${s}; inputRow = inputRow + ${e[1]}) { + for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${e[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batchB, + kStart + inputRow, + globalColStart + inputCol); + } + } + kStart = kStart + ${s}; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array; + for (var k = 0; k < ${s}; k++) { + for (var inner = 0; inner < ${m}; inner++) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${e[0]}]; + } + for (var innerRow = 0; innerRow < ${x}; innerRow++) { + let ACached = ${t?`mm_Asub[k][localRow + innerRow * ${e[1]}];`:`mm_Asub[localRow + innerRow * ${e[1]}][k];`} + for (var innerCol = 0; innerCol < ${m}; innerCol++) { + acc[innerRow][innerCol] = + fma(ACached, BCached[innerCol], acc[innerRow][innerCol]); + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < ${x}; innerRow++) { + let gRow = globalRowStart + localRow + innerRow * ${e[1]}; + for (var innerCol = 0; innerCol < ${m}; innerCol++) { + let gCol = globalColStart + localCol + innerCol * ${e[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` + let tileRow = i32(localId.y) * ${x}; + let tileCol = i32(localId.x) * ${m}; + + let globalRow = i32(globalId.y) * ${x}; + let globalCol = i32(globalId.x) * ${m}; + let globalRowStart = i32(workgroupId.y) * ${l}; + + let tileRowA = i32(localId.y) * ${d}; + let tileColA = i32(localId.x) * ${p}; + let tileRowB = i32(localId.y) * ${f}; + // Loop over shared dimension. + for (var t = 0; t < numTiles; t++) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${d}; innerRow++) { + for (var innerCol = 0; innerCol < ${p}; innerCol++) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${Mw(t)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${f}; innerRow++) { + for (var innerCol = 0; innerCol < ${m}; innerCol++) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batchB, + kStart + inputRow, + globalCol + innerCol); + } + } + kStart = kStart + ${s}; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array; + for (var k = 0; k < ${s}; k++) { + for (var inner = 0; inner < ${m}; inner++) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < ${x}; innerRow++) { + ${une(t)} + for (var innerCol = 0; innerCol < ${m}; innerCol++) { + acc[innerRow][innerCol] = + fma(ACached, BCached[innerCol], acc[innerRow][innerCol]); + } + } + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < ${x}; innerRow++) { + for (var innerCol = 0; innerCol < ${m}; innerCol++) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } + } + `;return` + var mm_Asub : array, ${h}>; + var mm_Bsub : array, ${s}>; + + ${De()} { + let batch = ${r?"0":"i32(globalId.z)"}; + let batchA = ${r||!a?"batch":"batch % uniforms.aShape[0]"}; + let batchB = ${r||!a?"batch":"batch % uniforms.bShape[0]"}; + let numTiles = ${r?`${Math.ceil(i/s)}`:`(uniforms.dimInner - 1) / ${s} + 1`}; + var kStart = ${r?`i32(globalId.z) * ${i}`:"0"}; + + var acc : array, ${x}>; + + // Without this initialization strange values show up in acc. + for (var innerRow = 0; innerRow < ${x}; innerRow++) { + for (var innerCol = 0; innerCol < ${m}; innerCol++) { + acc[innerRow][innerCol] = 0.0; + } + } + ${g} + } + `}const hne=n=>n?` + mm_readA(batchA, colA, globalRow), + mm_readA(batchA, colA + 1, globalRow), + mm_readA(batchA, colA + 2, globalRow), + mm_readA(batchA, colA + 3, globalRow) + `:` + mm_readA(batchA, globalRow, colA), + mm_readA(batchA, globalRow, colA + 1), + mm_readA(batchA, globalRow, colA + 2), + mm_readA(batchA, globalRow, colA + 3) + `;function dne(n,e=!1){N(n[1]===1&&n[2]===1,()=>`A linear work group size is required. But got ${n}.`);const t=n[0]*4;return` + var mm_Asub : array, ${n[0]}>; + + ${De()} { + let tileCol = i32(localId.x); + let globalCol = i32(globalId.x); + let globalRow = i32(globalId.y); + + let numTiles = (uniforms.dimInner - 1) / ${t} + 1; + let batch = i32(globalId.z); + let batchA = batch % uniforms.aShape[0]; + let batchB = batch % uniforms.bShape[0]; + // Without this initialization strange values show up in acc. + var acc = 0.0; + + // Loop over shared dimension. + for (var t = 0; t < numTiles; t++) { + // Load one tile of A into local memory. + let colA = t * ${t} + tileCol * 4; + mm_Asub[tileCol] = vec4(${hne(e)}); + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < ${t/4}; k++) { + let rowB = t * ${t} + k * 4; + let BCached = vec4(mm_readB(batchB, rowB, globalCol), + mm_readB(batchB, rowB + 1, globalCol), + mm_readB(batchB, rowB + 2, globalCol), + mm_readB(batchB, rowB + 3, globalCol)); + + let ACached = mm_Asub[k]; + acc = acc + dot(ACached, BCached); + } + + workgroupBarrier(); + } + + mm_write(batch, globalRow, globalCol, acc); + } + `}class pne{constructor(e,t,s=!1,r=!1,i=null,o=null,a=null,l=!1){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.outputShape=t,this.dispatchLayout={x:[2],y:[1],z:[0]};const c=s?e[1]:e[2];if(this.isVec4=(c%4===0&&!s||t[1]%4===0&&s)&&t[2]%4===0&&!r,this.outputComponent=this.isVec4?4:1,this.isVectorA=t[1]===1&&!s,!this.isVec4&&this.isVectorA)this.elementsPerThread=[1,1,1],this.workgroupSize=[32,1,1];else{const d=zee(t[1],c,t[2],s);this.workgroupSize=d.workgroupSize,this.elementsPerThread=d.elementsPerThread}this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread);const u=i!=null,h=a!=null;u&&this.variableNames.push("bias"),h&&this.variableNames.push("preluActivationWeights"),this.sequentialAccessByThreads=l,this.transposeA=s,this.transposeB=r,this.addBias=u,this.activation=o,this.hasPreluActivationWeights=h,[this.fitAOuter,this.fitBOuter,this.fitInner]=this.getShapeFit(t[1],t[2],c),this.shaderKey=`matMulPacked_${this.elementsPerThread}_${s}_${r}_${this.activation}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.isVectorA}_${this.sequentialAccessByThreads}`}getShapeFit(e,t,s){const r=this.workgroupSize[1]*this.elementsPerThread[1],i=this.workgroupSize[0]*this.elementsPerThread[0];!this.isVec4&&this.isVectorA?this.tileInner=this.workgroupSize[0]*4:this.tileInner=i;const o=e%r===0,a=t%i===0,l=s%this.tileInner===0;return[o,a,l]}getUserCode(){return` + ${Do(this.activation,this.hasPreluActivationWeights,this.isVec4)} + ${rb(this.addBias,this.activation,!1,this.transposeB,this.fitAOuter,this.fitBOuter,this.fitInner,this.isVec4?4:1)} + ${this.isVec4?eg(this.elementsPerThread,this.workgroupSize,this.transposeA,this.tileInner,!1,null,!0):this.isVectorA?dne(this.workgroupSize,this.transposeA):tg(this.elementsPerThread,this.workgroupSize,this.transposeA,this.tileInner,!1,null,this.sequentialAccessByThreads,!0)} + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fne(n){return` + var sumValues : array; + ${De()} { + let coords = getOutputCoords(); + let batch = coords[0]; + let batchA = batch % uniforms.aShape[0]; + let batchB = batch % uniforms.bShape[0]; + let row = coords[1]; + let col = coords[2]; + var sum = 0.0; + let Length = uniforms.dimInner; + for (var k = i32(localId.x); k < Length; k = k + ${n}) { + let dataA = mm_readA(batchA, row, k); + let dataB = mm_readB(batchB, k, col); + sum = sum + dataA * dataB; + } + sumValues[localId.x] = sum; + workgroupBarrier(); + + for(var currentSize = ${n/2}u; currentSize > 1u; + currentSize = currentSize / 2u) { + if (localId.x < currentSize) + { + sumValues[localId.x] = sumValues[localId.x] + sumValues[localId.x + currentSize]; + } + workgroupBarrier(); + } + + if (localId.x == 0u) { + sum = sumValues[0] + sumValues[1]; + mm_write(batch, row, col, sum); + } + } + `}class mne{constructor(e,t=!1,s=!1,r=null,i=null,o=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workgroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout={x:[],y:[1,2],z:[0]},this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize);const a=r!=null,l=o!=null;a&&this.variableNames.push("bias"),l&&this.variableNames.push("preluActivationWeights"),this.transposeA=t,this.transposeB=s,this.addBias=a,this.activation=i,this.hasPreluActivationWeights=l,this.shaderKey=`matMulReduce_${this.activation}_${t}_${s}`}getUserCode(){return` + ${Do(this.activation,this.hasPreluActivationWeights)} + ${rb(this.addBias,this.activation,this.transposeA,this.transposeB)} + ${fne(this.workgroupSize[0])} + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gne(n){const e=n[1],t=n[0],s=e>t?e:t;return` + var mm_Asub : array, ${e}>; + var mm_Bsub : array, ${s}>; + + // If the output size is small for matrix multiplication, avoid to use vec4 + // and handle some elements per thread to optimally utilize the ALU. + // Read data from global memory to registers firstly, then store them into + // shared memory, so it is instruction-Level parallelism for arithmetic + // operations and others handle IO operations between barrier api, makes ALU + // and load/store units work simultaneously, could improves the performance. + ${De()} { + let tileRow = i32(localId.y); + let tileCol = i32(localId.x); + let globalRow = i32(globalId.y); + let globalCol = i32(globalId.x); + let batch = i32(globalId.z); + let batchA = batch % uniforms.aShape[0]; + let batchB = batch % uniforms.bShape[0]; + + // uniforms.dimInner should be greater than 0. + let numTiles = (uniforms.dimInner - 1) / ${s} + 1; + var acc = 0.0; + + var globalColA = tileCol; + var globalRowB = 0; + var regA = mm_readA(batchA, globalRow, globalColA); + var regB0 = mm_readB(batchB, globalRowB + 2 * tileRow, globalCol); + var regB1 = mm_readB(batchB, globalRowB + 2 * tileRow + 1, globalCol); + globalColA = globalColA + ${s}; + globalRowB = globalRowB + ${s}; + + for (var t = 0; t < numTiles; t = t + 1) { + mm_Asub[tileRow][tileCol] = regA; + mm_Bsub[2 * tileRow][tileCol] = regB0; + mm_Bsub[2 * tileRow + 1][tileCol] = regB1; + + workgroupBarrier(); + + regA = mm_readA(batchA, globalRow, globalColA); + regB0 = mm_readB(batchB, globalRowB + 2 * tileRow, globalCol); + regB1 = mm_readB(batchB, globalRowB + 2 * tileRow + 1, globalCol); + globalColA = globalColA + ${s}; + globalRowB = globalRowB + ${s}; + + for (var k = 0; k < ${s}; k = k + 1) { + acc = acc + mm_Asub[tileRow][k] * mm_Bsub[k][tileCol]; + } + workgroupBarrier(); + } + + mm_write(batch, globalRow, globalCol, acc); + } + `}class xne{constructor(e,t,s,r=!1,i=!1,o=null,a=null,l=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workgroupSize=[16,8,1],this.outputShape=s,this.dispatchLayout={x:[2],y:[1],z:[0]},this.dispatch=[Math.ceil(s[2]/this.workgroupSize[0]),Math.ceil(s[1]/this.workgroupSize[1]),s[0]];const c=o!=null;c&&this.variableNames.push("bias");const u=l!=null;u&&this.variableNames.push("preluActivationWeights"),this.transposeA=r,this.transposeB=i,this.addBias=c,this.activation=a,this.hasPreluActivationWeights=u,this.shaderKey=`matMulSmallOutputSize_${this.activation}_${r}_${i}`}getUserCode(){return` + ${Do(this.activation,this.hasPreluActivationWeights)} + ${rb(this.addBias,this.activation,this.transposeA,this.transposeB)} + ${gne(this.workgroupSize)} + `}}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class vne{constructor(e,t,s=!1,r=!1){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workgroupSize=[8,8,1],this.atomic=!0,this.splitedDimInner=128,N(e[0]===1,()=>"MatMulSplitKProgram only supports batch = 1."),this.outputShape=e,this.dispatchLayout={x:[2],y:[1],z:[0,3]};const i=(s&&this.outputShape[1]%4===0||!s&&t%4===0)&&this.outputShape[2]%4===0;this.elementsPerThread=[4,4,this.splitedDimInner],this.outputComponent=i?4:1,i||(this.outputShape[1]<16&&(this.elementsPerThread[1]=1),this.outputShape[2]<16&&(this.elementsPerThread[0]=1)),this.dispatch=Le(this.dispatchLayout,[this.outputShape[0],this.outputShape[1],this.outputShape[2],t],this.workgroupSize,this.elementsPerThread),this.transposeA=s,this.transposeB=r,this.shaderKey=`matMulSplitK_${s}_${r}_${this.elementsPerThread}_${this.outputComponent}`}getUserCode(){const e=this.outputComponent;return` + ${mk(!1,this.transposeB,!1,!1,!1,e)} + fn mm_write(batch: i32, row : i32, col : i32, value : ${Rt(e)}) { + if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) { + let coords = vec3(batch, row, col); + let flatIndex = getOutputIndexFromCoords(coords); + // The problem is that we should initialize output to zero before using. + // Otherwise, the original value will be added to the result. + for (var i = 0; i < ${e}; i = i + 1) { + ${Aa("&result[flatIndex + i]",`${e>1?"value[i]":"value"}`,"float32")} + } + } + } + ${e===4?eg(this.elementsPerThread,this.workgroupSize,this.transposeA,32,!0,this.splitedDimInner):tg(this.elementsPerThread,this.workgroupSize,this.transposeA,32,!0,this.splitedDimInner)} + `}}class bne{constructor(e,t=null,s=null,r=null){this.uniforms="",this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.addBias=t!=null,this.hasPreluActivationWeights=r!=null,this.activation=s,this.addBias&&this.variableNames.push("bias"),this.hasPreluActivationWeights&&this.variableNames.push("preluActivationWeights"),this.shaderKey=`biasActivation_${s}`}getUserCode(){return` + ${Do(this.activation,this.hasPreluActivationWeights)} + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + var value = getXByOutputIndex(index); + ${Wl(this.addBias,this.activation)} + setOutputAtIndex(index, value); + } + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class yne{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="value : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="fill"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + setOutputAtIndex(index, uniforms.value); + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sr(n){const{backend:e,attrs:t}=n,{shape:s,value:r}=t;let{dtype:i}=t;if(i=i||Il(r),i==="string"){const o=Pn(i,re(s));return o.fill(r),e.makeTensorInfo(s,i,o)}else{const o=new yne(s),a=[{type:"float32",data:[r]}];return e.runWebGPUProgram(o,[],i,a)}}const wne={kernelName:B0,backendName:"webgpu",kernelFunc:sr};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function tt(n){const{inputs:e,attrs:t}=n,{x:s}=e,{shape:r}=t,i=re(s.shape),o=r2(r,i),a=re(o);return N(i===a,()=>`The new shape (${o}) has ${a} elements and the old shape (${s.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),n.backend.incRef(s.dataId),{dataId:s.dataId,shape:o,dtype:s.dtype}}const Sne={kernelName:Vd,backendName:"webgpu",kernelFunc:tt};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ng({a:n,b:e,transposeA:t,transposeB:s,backend:r,bias:i=null,preluActivationWeights:o=null,leakyreluAlpha:a=0,activation:l=null}){const c=n.shape.length,u=e.shape.length,h=t?n.shape[c-2]:n.shape[c-1],d=s?e.shape[u-1]:e.shape[u-2],p=t?n.shape[c-1]:n.shape[c-2],f=s?e.shape[u-2]:e.shape[u-1],x=n.shape.slice(0,-2),m=e.shape.slice(0,-2),g=re(x),v=re(m),y=pt(n.shape.slice(0,-2),e.shape.slice(0,-2)).concat([p,f]);N(h===d,()=>`Error in matMul: inner shapes (${h}) and (${d}) of Tensors with shapes ${n.shape} and ${e.shape} and transposeA=${t} and transposeB=${s} must match.`);const w=t?[g,h,p]:[g,p,h],C=s?[v,f,d]:[v,d,f],T=tt({inputs:{x:n},backend:r,attrs:{shape:w}}),E=tt({inputs:{x:e},backend:r,attrs:{shape:C}}),R=[T,E],_=Math.max(g,v),k=[T,E],F=[{type:"int32",data:[p]},{type:"int32",data:[f]},{type:"int32",data:[h]}];let B,M;const P=[_,p,f];let L=oe().get("WEBGPU_MATMUL_PROGRAM_TYPE");if(L<0){const U=oe().getNumber("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL"),X=U>0?U:r.thresholdToIncreaseWorkgroups,K=_*Math.ceil(p/32)*Math.ceil(f/32);K<=X||p<=8&&K<=X*2?_*p*f<=128?L=$i.MatMulReduceProgram:_===1&&d>=2e3?L=$i.MatMulSplitKProgram:L=$i.MatMulSmallOutputSizeProgram:L=$i.MatMulPackedProgram}switch(L){case $i.MatMulReduceProgram:B=new mne(P,t,s,i,l,o);break;case $i.MatMulSplitKProgram:{if(M=sr({backend:r,attrs:{shape:P,value:0,dtype:n.dtype}}),B=new vne(P,d,t,s),i||l){M=r.runWebGPUProgram(B,k,n.dtype,F,M);const X=new bne(M.shape,i,l,o);let K=null;const J=[M];i&&J.push(i),o&&J.push(o),l==="leakyrelu"&&(K=[{type:"float32",data:[a]}],X.uniforms+=" alpha : f32,");const ae=r.runWebGPUProgram(X,J,M.dtype,K);R.push(M);const he=tt({inputs:{x:ae},backend:r,attrs:{shape:y}});R.push(ae);for(const j of R)r.disposeData(j.dataId);return he}break}case $i.MatMulSmallOutputSizeProgram:B=new xne(w,C,P,t,s,i,l,o);break;case $i.MatMulPackedProgram:const U=r.adapterInfo.isIntel();B=new pne(w,P,t,s,i,l,o,U);break;default:throw new Error(`Unsupported MatMulProgramType ${L}.`)}i&&k.push(i),o&&k.push(o),l==="leakyrelu"&&(F.push({type:"float32",data:[a]}),B.uniforms+=" alpha : f32,"),M=r.runWebGPUProgram(B,k,n.dtype,F,M);const q=tt({inputs:{x:M},backend:r,attrs:{shape:y}});R.push(M);for(const U of R)r.disposeData(U.dataId);return q}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Cne(n){const{inputs:e,backend:t,attrs:s}=n,{a:r,b:i,bias:o,preluActivationWeights:a}=e,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:h}=s;return ng({a:r,b:i,transposeA:l,transposeB:c,backend:t,bias:o,preluActivationWeights:a,leakyreluAlpha:h,activation:u})}const _ne={kernelName:Ph,backendName:"webgpu",kernelFunc:Cne};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Nw{constructor(e,t,s){this.variableNames=["AReal","AImag","BReal","BImag"],this.workgroupSize=[128,1,1],this.size=!0,this.outputShape=pt(t,s),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey=`binaryOpComplex_${e}`,this.op=e}getUserCode(){return` + fn binaryOpComplex( + areal : f32, aimag : f32, breal : f32, bimag : f32) -> f32 { + ${sb(this.op,!1)} + } + + ${De("index")} { + if(index < uniforms.size) { + let areal = getARealByOutputIndex(index); + let aimag = getAImagByOutputIndex(index); + let breal = getBRealByOutputIndex(index); + let bimag = getBImagByOutputIndex(index); + setOutputAtIndex(index, binaryOpComplex(areal, aimag, breal, bimag)); + } + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class r0{constructor(e,t,s){if(this.size=!0,this.variableNames=["A","B"],this.outputShape=pt(t,s),this.dispatchLayout=Xe(this.outputShape),this.op=e,this.useSharedMemoryWithA=t.length<=1&&s.length>1&&t[0]<128,this.useSharedMemoryWithB=s.length<=1&&t.length>1&&s[0]<128,this.useSharedMemoryWithA||this.useSharedMemoryWithB)this.outputComponent=1,this.variableComponents=[1,1],this.lastDimensionSize=this.useSharedMemoryWithB?s[0]:t[0],this.shaderKey=`binary_${e}_${this.lastDimensionSize}`,this.type="shared",this.workgroupSize=[256,1,1];else{const r=t.length>0&&t[t.length-1]%4===0,i=s.length>0&&s[s.length-1]%4===0;r&&i?(this.outputComponent=4,this.variableComponents=[4,4]):r&&(Pb(s)||s[s.length-1]===1)||i&&(Pb(t)||t[t.length-1]===1)?(this.outputComponent=4,this.variableComponents=r?[4,1]:[1,4]):(this.outputComponent=1,this.variableComponents=[1,1]),this.type="nonshared",this.shaderKey=`binary_${e}_${this.variableComponents}`,this.workgroupSize=[128,1,1]}this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.outputComponent,1,1])}getUserCode(){let e;const t=this.outputComponent===4?"vec4":"f32",s=` + fn binaryOperation(a : ${t}, b : ${t}) -> ${t} { + ${sb(this.op,this.outputComponent===4)} + }; + `;if(this.type==="shared"){const r=this.lastDimensionSize>1?`coords[${this.outputShape.length-1}]`:"0",i=this.useSharedMemoryWithB?`let a = getAByOutputIndex(index); + let b = sharedBuf[${r}];`:`let a = sharedBuf[${r}]; + let b = getBByOutputIndex(index);`;e=` + ${s} + var sharedBuf : array; + ${De("index")} { + // Fill in the shared memory buffer. + let localIndex = i32(localId.x); + if(localIndex < ${this.lastDimensionSize}) { + sharedBuf[localIndex] = f32(${this.useSharedMemoryWithB?"B":"A"}[localIndex]); + } + workgroupBarrier(); + + if(index < uniforms.size) { + let coords = getCoordsFromIndex(index); + ${i} + setOutputAtIndex(index, binaryOperation(a, b)); + } + } + `}else e=` + ${s} + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index * ${this.outputComponent}); + let a = ${t}(getAByOutputCoords(coords)); + let b = ${t}(getBByOutputCoords(coords)); + setOutputAtIndex(index, binaryOperation(a, b)); + } + } + `;return e}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function br(n){const{inputs:e}=n,{x:t}=e;return n.backend.incRef(t.dataId),{dataId:t.dataId,shape:t.shape,dtype:t.dtype}}const Tne={kernelName:gu,backendName:"webgpu",kernelFunc:br};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Gl(n){const{inputs:e,backend:t}=n,{real:s,imag:r}=e,i=t.makeTensorInfo(s.shape,"complex64"),o=t.tensorMap.get(i.dataId),a=br({inputs:{x:s},backend:t}),l=br({inputs:{x:r},backend:t});return o.complexTensorInfos={real:a,imag:l},i}const Ine={kernelName:E0,backendName:"webgpu",kernelFunc:Gl};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class rh{constructor(e,t,s=""){this.variableNames=["A"],this.size=!0;const r=128;this.workgroupSize=[r,1,1],this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.op=t,s!==""&&(this.uniforms=s),this.shaderKey=`unary_${t}`}getUserCode(){return` + fn unaryOperation(a : f32) -> f32 { + ${Ga(this.op,!1)} + } + ${De("index")} { + if (index < uniforms.size) { + let a = getAByOutputIndex(index); + setOutputAtIndex(index, unaryOperation(a)); + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jt({opType:n,cpuKernelImpl:e,dtype:t}){return({inputs:s,backend:r})=>{const{x:i}=s,o=r,a=t||i.dtype;if(o.shouldExecuteOnCPU([i])&&e!=null){const c=o.tensorMap.get(i.dataId),u=e(c.values,a);return o.makeTensorInfo(i.shape,a,u)}const l=new rh(i.shape,n);return o.runWebGPUProgram(l,[i],a)}}function xs({opType:n,cpuKernelImpl:e,supportsComplex:t=!1,dtype:s}){return({inputs:r,backend:i})=>{const{a:o,b:a}=r,l=i;if(t&&o.dtype==="complex64"){const h=l.tensorMap.get(o.dataId),d=l.tensorMap.get(a.dataId);let p,f;if(n!==bt.MUL)[p,f]=[[h.complexTensorInfos.real,d.complexTensorInfos.real],[h.complexTensorInfos.imag,d.complexTensorInfos.imag]].map(m=>{const[g,v]=m,b={dataId:g.dataId,dtype:g.dtype,shape:o.shape},y={dataId:v.dataId,dtype:v.dtype,shape:a.shape},w=new r0(n,o.shape,a.shape);return l.runWebGPUProgram(w,[b,y],ds(g.dtype,v.dtype))});else{const m=new Nw(bt.COMPLEX_MULTIPLY_REAL,o.shape,a.shape),g=new Nw(bt.COMPLEX_MULTIPLY_IMAG,o.shape,a.shape),v=[{dataId:h.complexTensorInfos.real.dataId,dtype:h.complexTensorInfos.real.dtype,shape:o.shape},{dataId:h.complexTensorInfos.imag.dataId,dtype:h.complexTensorInfos.imag.dtype,shape:o.shape},{dataId:d.complexTensorInfos.real.dataId,dtype:d.complexTensorInfos.real.dtype,shape:a.shape},{dataId:d.complexTensorInfos.imag.dataId,dtype:d.complexTensorInfos.imag.dtype,shape:a.shape}];p=l.runWebGPUProgram(m,v,"float32"),f=l.runWebGPUProgram(g,v,"float32")}const x=Gl({inputs:{real:p,imag:f},backend:l});return l.disposeData(p.dataId),l.disposeData(f.dataId),x}const c=s||ds(o.dtype,a.dtype);if((o.dtype==="string"||a.dtype==="string"||l.shouldExecuteOnCPU([o,a]))&&e!=null){const h=l.tensorMap.get(o.dataId).values,d=l.tensorMap.get(a.dataId).values,p=o.dtype==="string"?Ti(h):h,f=o.dtype==="string"?Ti(d):d,[x,m]=e(o.shape,a.shape,p,f,c);return l.makeTensorInfo(m,c,x)}const u=new r0(n,o.shape,a.shape);return l.runWebGPUProgram(u,[o,a],c)}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const{addImpl:Ene,castImpl:kne,ceilImpl:Ane,concatImpl:Rne,equalImpl:Mne,expImpl:Nne,expm1Impl:$ne,floorImpl:Dne,floorDivImpl:Pne,gatherNdImpl:Lne,gatherV2Impl:Fne,greaterEqualImpl:One,greaterImpl:zne,lessEqualImpl:Bne,lessImpl:Une,logImpl:Vne,maxImpl:Wne,maximumImpl:Gne,minimumImpl:Hne,multiplyImpl:qne,negImpl:Xne,notEqualImpl:Kne,prodImpl:jne,rangeImpl:Yne,rsqrtImpl:Zne,scatterImpl:Jne,simpleAbsImpl:Qne,sliceImpl:ese,stridedSliceImpl:tse,stringNGramsImpl:nse,subImpl:sse,tileImpl:rse,topKImpl:ise,transposeImpl:ose}=nE;/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ase=jt({opType:Me.ABS,cpuKernelImpl:Qne}),lse={kernelName:td,backendName:"webgpu",kernelFunc:ase};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cse=jt({opType:Me.ACOS}),use={kernelName:Yc,backendName:"webgpu",kernelFunc:cse};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hse=jt({opType:Me.ACOSH}),dse={kernelName:Zc,backendName:"webgpu",kernelFunc:hse};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pse=xs({opType:bt.ADD,cpuKernelImpl:Ene,supportsComplex:!0}),fse={kernelName:El,backendName:"webgpu",kernelFunc:pse};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class mse{constructor(e){this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e[0],this.variableNames=e.map((t,s)=>`T${s}`),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.shaderKey="addN"}getUserCode(){const e=[];this.variableNames.forEach(r=>{e.push(`let v${r} = get${r}ByOutputCoords(coords);`)});const t=this.variableNames.map(r=>`v${r}`).join(" + ");return` + ${De("index")} { + for (var i = 0; i < ${this.workPerThread}; i = i + 1) { + let flatIndex = index * ${this.workPerThread} + i; + if (flatIndex < uniforms.size) { + let coords = getCoordsFromIndex(flatIndex); + ${e.join(` + `)} + setOutputAtIndex(flatIndex, ${t}); + } + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gse(n){const{inputs:e,backend:t}=n,s=e;if(s.length===1)return br({inputs:{x:s[0]},backend:t});const r=s.map(a=>a.dtype).reduce((a,l)=>ds(a,l)),i=s.map(a=>a.shape),o=new mse(i);return t.runWebGPUProgram(o,s,r)}const xse={kernelName:w0,backendName:"webgpu",kernelFunc:gse};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class vse{constructor(e,t){this.variableNames=["A"],this.workgroupSize=[16,16,1];const s=new Array(e.length);for(let r=0;r`Must be a square tile, current tile shape is ${this.workgroupSize[0]} x ${this.workgroupSize[1]}`);const e=this.workgroupSize[0];return` + var tile : array, ${this.workgroupSize[0]}>; + ${De()} { + var x = i32(workgroupId.x) * ${e} + i32(localId.x); + var y = i32(workgroupId.y) * ${e} + i32(localId.y); + let width = uniforms.outShape[0]; + let height = uniforms.outShape[1]; + if (x < width && y < height) { + tile[localId.y][localId.x] = f32(A[y * width + x]); + } + workgroupBarrier(); + + x = i32(workgroupId.y) * ${e} + i32(localId.x); + y = i32(workgroupId.x) * ${e} + i32(localId.y); + if (x < height && y < width) { + setOutputAtIndex((y * height + x), tile[localId.x] + [localId.y]); + } + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class bse{constructor(e,t){this.variableNames=["A"],this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0;const s=new Array(e.length);for(let r=0;r6)throw Error(`Transpose for rank ${e} is not yet supported`);const t=new Array(e);for(let s=0;s=32768&&s>=512?this.workgroupSize=[512,1,1]:e.inSize>=4096?this.workgroupSize=[256,1,1]:this.workgroupSize=[64,1,1],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,[1,1,1]),this.reduceType=t,this.shaderKey=`reduce_${t}`}getUserCode(){let e="",t="0.0";const s=this.workgroupSize[0];this.reduceType==="min"||this.reduceType==="max"?(e=` + if (isnan(candidate)) { + bestValue = uniforms.NAN; + } else if (!isnan(bestValue) && candidate ${this.reduceType==="min"?"<":">"} bestValue) + { bestValue = candidate; }`,t="f32(x[offset])"):this.reduceType==="sum"||this.reduceType==="mean"?e=" bestValue = bestValue + candidate; ":this.reduceType==="prod"?(e=" bestValue = bestValue * candidate; ",t="1.0"):this.reduceType==="all"?(e=" bestValue = f32(bestValue >= 1.0 && candidate >= 1.0); ",t="1.0"):this.reduceType==="any"&&(e=" bestValue = f32(bestValue >= 1.0 || candidate >= 1.0); ",t="0.0");const r=this.reduceType==="mean"?"setOutputAtIndex(outputIndex, bestValue / f32(uniforms.reduceSize));":"setOutputAtIndex(outputIndex, bestValue);";return` + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + + ${` + var xBestValues : array; + `} + fn getOffset(outputIndex : i32) -> i32 { + let outputCoords = getCoordsFromIndex(outputIndex); + let offset = ${this.outputShape.length===1?"outputCoords":"outputCoords[0]"} * uniforms.reduceSize; + return offset; + } + ${De("index")} { + let outputIndex = index / ${s}; + let offset = getOffset(outputIndex); + var bestValue = ${t}; + let Length = uniforms.reduceSize; + let WorkPerThread = DIV_CEIL(u32(Length), ${s}u); + for (var k = i32(localId.x); k < Length && outputIndex < uniforms.size; + k = k + ${s}) { + let candidate = f32(x[offset + k]); + ${e} + } + xBestValues[localId.x] = bestValue; + workgroupBarrier(); + + var reduceSize = min(u32(Length), ${s}u); + for (var currentSize = reduceSize / 2u; reduceSize > 1u; + currentSize = reduceSize / 2u) { + let interval = DIV_CEIL(reduceSize, 2u); + if (localId.x < currentSize) { + let candidate = xBestValues[localId.x + interval]; + ${e} + xBestValues[localId.x] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (localId.x == 0u && outputIndex < uniforms.size) { + ${r} + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Sse={mean:"float32",all:"bool",any:"bool"};function Hl(n,e,t,s,r){const i=n.shape.length,o=[],a=It(e,n.shape);let l=a;const c=ln(l,i);let u=n;c!=null&&(u=to({inputs:{x:n},attrs:{perm:c},backend:r}),l=xn(l.length,i),o.push(u)),Kn(s,l,i);const[h,d]=Wn(u.shape,l);let p=h;t&&(p=Vn(h,a));let f;if((s==="max"||s==="prod")&&r.shouldExecuteOnCPU([u])){const x=r.tensorMap.get(u.dataId).values;switch(s){case"max":const m=Wne(x,re(d),p,n.dtype);f=r.makeTensorInfo(p,n.dtype,m);break;case"prod":const{outVals:g,outShape:v,outDtype:b}=jne(u.shape,u.dtype,x,l);f=r.makeTensorInfo(v,b,g);break;default:throw new Error(`${s} CPU implementation is not yet supported.`)}}else{const x=re(d),g=re(u.shape)/x,v={windowSize:x,inSize:x,batchSize:g,outSize:1},b=Sse[s]||im(n.dtype),y=[{type:"int32",data:[x]}],w=new wse(v,s,r.device.limits.maxComputeWorkgroupSizeX),C=r.runWebGPUProgram(w,[u],b,y);o.push(C),f=tt({inputs:{x:C},attrs:{shape:p},backend:r})}return o.forEach(x=>r.disposeData(x.dataId)),f}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Cse(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{keepDims:i,axis:o}=s;return Hl(r,o,i,"all",t)}const _se={kernelName:S0,backendName:"webgpu",kernelFunc:Cse};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Tse(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{keepDims:i,axis:o}=s;return Hl(r,o,i,"any",t)}const Ise={kernelName:C0,backendName:"webgpu",kernelFunc:Tse};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class xk{constructor(e,t,s){this.workgroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="infinityValue : f32,",this.size=!0;const r=[t];this.op=s==="min"?"<":">";const[i,o]=Wn(e,r);this.outputShape=i.length===0?[1]:i,this.dispatchLayout=Xe(this.outputShape),re(o)<32?(this.type="plain",this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize)):(this.type="shared",this.dispatch=Le(this.dispatchLayout,this.outputShape,[1,1,1])),this.inputShape=e,this.shaderKey=`argMinMax_${this.op}_${this.type}`}getUserCode(){const e=this.workgroupSize[0],t=()=>this.inputShape.length===1?"uniforms.xShape":`uniforms.xShape.${Io(this.inputShape.length-1)}`,s=()=>{let r="";if(this.outputShape.length===1)this.inputShape.length!==1&&(r+="outputCoords,");else for(let i=0;i u32 { + return ((a - 1u) / b + 1u); + } + + ${` + var xBestIndices : array; + var xBestValues : array; + `} + + ${De("index")} { + let outputIndex = index / ${e}; + let reduceLength = ${t()}; + + var bestIndex = i32(localId.x); + var bestValue = uniforms.infinityValue; + let outputCoords = getCoordsFromIndex(outputIndex); + for (var k = i32(localId.x); k < reduceLength && outputIndex < uniforms.size; + k = k + ${e}) { + let candidate = getX(${s()} k); + if (!isnan(candidate) && candidate ${this.op} bestValue) { + bestValue = candidate; + bestIndex = k; + } + } + xBestValues[localId.x] = bestValue; + xBestIndices[localId.x] = bestIndex; + workgroupBarrier(); + + var reduceSize = min(u32(reduceLength), ${e}u); + for (var currentSize = reduceSize / 2u; reduceSize > 1u; + currentSize = reduceSize / 2u) { + let interval = DIV_CEIL(reduceSize, 2u); + if (localId.x < currentSize) { + let candidate = xBestValues[localId.x + interval]; + if (candidate ${this.op} bestValue) { + bestValue = candidate; + xBestValues[localId.x] = bestValue; + xBestIndices[localId.x] = xBestIndices[localId.x + interval]; + } + } + reduceSize = interval; + workgroupBarrier(); + } + + if (localId.x == 0u && outputIndex < uniforms.size) { + setOutputAtIndexI32(outputIndex, xBestIndices[localId.x]); + } + } + `:` + ${De("index")} { + if (index < uniforms.size) { + let outputCoords = getCoordsFromIndex(index); + var bestIndex = 0; + var bestValue = getX(${s()} 0); + let reduceLength = ${t()}; + for (var i = 1; i < reduceLength; i++) { + let candidate = getX(${s()} i); + if (candidate ${this.op} bestValue) { + bestValue = candidate; + bestIndex = i; + } + } + setOutputAtIndexI32(index, bestIndex); + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ese(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i}=s;let o=It(i,r.shape);const a=ln(o,r.shape.length);let l=r;const c=[];a!=null&&(l=to({inputs:{x:r},backend:t,attrs:{perm:a}}),c.push(l),o=xn(o.length,l.shape.length)),Kn("argMax",[o[0]],l.shape.length);const u=new xk(l.shape,o[0],"max"),h=[{type:"float32",data:[Number.NEGATIVE_INFINITY]}],d=t.runWebGPUProgram(u,[l],"int32",h);return c.forEach(p=>t.disposeData(p.dataId)),d}const kse={kernelName:nd,backendName:"webgpu",kernelFunc:Ese};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ase(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i}=s;let o=It(i,r.shape);const a=ln(o,r.shape.length);let l=r;const c=[];a!=null&&(l=to({inputs:{x:r},backend:t,attrs:{perm:a}}),c.push(l),o=xn(o.length,l.shape.length)),Kn("argMin",[o[0]],l.shape.length);const u=new xk(l.shape,o[0],"min"),h=[{type:"float32",data:[Number.POSITIVE_INFINITY]}],d=t.runWebGPUProgram(u,[l],"int32",h);return c.forEach(p=>t.disposeData(p.dataId)),d}const Rse={kernelName:sd,backendName:"webgpu",kernelFunc:Ase};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Mse=jt({opType:Me.ASIN}),Nse={kernelName:Jc,backendName:"webgpu",kernelFunc:Mse};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $se=jt({opType:Me.ASINH}),Dse={kernelName:Qc,backendName:"webgpu",kernelFunc:$se};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Pse=jt({opType:Me.ATAN}),Lse={kernelName:eu,backendName:"webgpu",kernelFunc:Pse};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Fse=xs({opType:bt.ATAN2}),Ose={kernelName:nu,backendName:"webgpu",kernelFunc:Fse};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const zse=jt({opType:Me.ATANH}),Bse={kernelName:tu,backendName:"webgpu",kernelFunc:zse};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Use{constructor(e){this.variableNames=["x"],this.uniforms="strides : vec2,",this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="poolWithFilterSizeEqualsOne"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords[0]; + let d = coords[3]; + + let xRCCorner = coords.yz * uniforms.strides; + let xRCorner = xRCCorner.x; + let xCCorner = xRCCorner.y; + + let value = getX(batch, xRCorner, xCCorner, d); + setOutputAtIndex(index, value); + } + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Yh{constructor(e,t,s=!1,r=!1,i=!1){if(this.variableNames=["x"],this.uniforms="strides : vec2, pads : vec2, dilations : vec2, convDims : vec2, filterDims : vec2,",this.workgroupSize=[128,1,1],this.size=!0,t==="avg"&&s)throw new Error("Cannot compute positions for average pool.");this.outputShape=e.outShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.poolType=t,this.computePositions=s,this.flattenPositions=r,this.includeBatchIndex=i,this.shaderKey=`pool2D_${t}_${s}_${r}_${i}`}getUserCode(){let e;this.poolType==="avg"?e="resultValue = resultValue + value; count = count + 1.0;":this.computePositions?e=`let currMaxValue = mix(value, maxValue, maxValueFound); + if (value >= currMaxValue) { + maxValue = value; + maxValueFound = 1.0; + maxPosition = ${this.flattenPositions?this.includeBatchIndex?"((batch * uniforms.xShape[1] + xR) * uniforms.xShape[2] + xC) * uniforms.xShape[3] + d":"(xR * uniforms.xShape[2] + xC) * uniforms.xShape[3] + d":"wR * uniforms.filterDims.y + wC"}; + }`:e="resultValue = max(value, resultValue);";let t="resultValue";return this.poolType==="avg"&&(t="resultValue / max(count, 1.0)"),` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords[0]; + let d = coords[3]; + let xRCCorner = vec2(coords.yz) * uniforms.strides - uniforms.pads; + let xRCorner = xRCCorner.x; + let xCCorner = xRCCorner.y; + + ${this.computePositions?`var maxValue = 0.0; + var maxValueFound = 0.0; + var maxPosition = 0;`:`var resultValue = ${this.poolType==="avg"?"0.0":"-1.0 / pow(10.0, -20.0)"};`} + + var count = 0.0; + for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + uniforms.dilations.x) { + let xR = xRCorner + wR; + + if (xR < 0 || xR >= uniforms.convDims.x) { + continue; + } + + for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + uniforms.dilations.y) { + let xC = xCCorner + wC; + if (xC < 0 || xC >= uniforms.convDims.y) { + continue; + } + + let value = getX(batch, xR, xC, d); + ${e} + } + } + + ${this.computePositions?"setOutputAtIndexI32(index, maxPosition);":`setOutputAtIndex(index, ${t});`} + } + } + `}}class ib{constructor(e,t,s=!1,r=!1,i=!1){if(this.variableNames=["x"],this.uniforms="strides : vec3, pads : vec3, convDims : vec3, filterDims : vec3,",this.workgroupSize=[128,1,1],this.size=!0,t==="avg"&&s)throw new Error("Cannot compute positions for average pool.");this.outputShape=e.outShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.poolType=t,this.computePositions=s,this.flattenPositions=r,this.includeBatchIndex=i,this.shaderKey=`pool3D_${t}_${s}_${r}_${i}`}getUserCode(){let e;this.poolType==="avg"?e="resultValue += value; count += 1.0;":this.computePositions?e=`let currMaxValue = mix(value, maxValue, maxValueFound); + if (value >= currMaxValue) { + maxValue = value; + maxValueFound = 1.0; + maxPosition = ${this.flattenPositions?this.includeBatchIndex?"(((batch * uniforms.xShape.y + xD) * uniforms.xShape.z + xR) * uniforms.xShape.w + xC) * uniforms.xShape.u + ch":"((xD * uniforms.xShape.z + xR) * uniforms.xShape.w + xC) * uniforms.xShape.u + ch":"wD * uniforms.filterDims.y * uniforms.filterDims.y + wR * uniforms.filterDims.z + wC"}; + }`:e="resultValue = max(value, resultValue);";let t="resultValue";return this.poolType==="avg"&&(t="resultValue / max(count, 1.0)"),` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords.x; + let ch = coords.u; + + let xCorner = vec3(coords.y, coords.z, coords.w) * uniforms.strides - uniforms.pads; + let xDCorner = xCorner.x; + let xRCorner = xCorner.y; + let xCCorner = xCorner.z; + + ${this.computePositions?`var maxValue = 0.0; + var maxValueFound = 0.0; + var maxPosition = 0;`:`var resultValue = ${this.poolType==="avg"?"0.0":"-1.0 / pow(10.0, -20.0)"};`} + + var count = 0.0; + for (var wD = 0; wD < uniforms.filterDims.x; wD++) { + let xD = xDCorner + wD; + if (xD < 0 || xD >= uniforms.convDims.x) { + continue; + } + + for (var wR = 0; wR < uniforms.filterDims.y; wR++) { + let xR = xRCorner + wR; + if (xR < 0 || xR >= uniforms.convDims.y) { + continue; + } + + for (var wC = 0; wC < uniforms.filterDims.z; wC++) { + let xC = xCCorner + wC; + if (xC < 0 || xC >= uniforms.convDims.z) { + continue; + } + + let value = getX(batch, xD, xR, xC, ch); + ${e} + } + } + } + + ${this.computePositions?"setOutputAtIndexI32(index, maxPosition);":`setOutputAtIndex(index, ${t});`} + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vk(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{reductionIndices:i,keepDims:o}=s;return Hl(r,i,o,"max",t)}const Vse={kernelName:kd,backendName:"webgpu",kernelFunc:vk};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bk(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{keepDims:i,axis:o}=s;return Hl(r,o,i,"mean",t)}const Wse={kernelName:Md,backendName:"webgpu",kernelFunc:bk};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yk(n,e,t,s){if(e.filterWidth===1&&e.filterHeight===1&&Wt(e.inShape,e.outShape))return br({inputs:{x:n},backend:s});if(e.filterWidth===e.inWidth&&e.filterHeight===e.inHeight&&e.batchSize===1&&e.padInfo.type==="VALID"){const o=n.shape.length,a=tt({inputs:{x:n},backend:s,attrs:{shape:[n.shape[o-3]*n.shape[o-2],n.shape[o-1]]}});let l;t==="avg"?l=bk({inputs:{x:a},backend:s,attrs:{axis:0,keepDims:!1}}):(N(t==="max",()=>`Invalid pool type ${t}`),l=vk({inputs:{x:a},backend:s,attrs:{reductionIndices:0,keepDims:!1}}));const c=tt({inputs:{x:l},backend:s,attrs:{shape:e.outShape}});return s.disposeData(a.dataId),s.disposeData(l.dataId),c}let r;const i=[{type:"int32",data:[e.strideHeight,e.strideWidth]}];return e.filterHeight===1&&e.filterWidth===1?r=new Use(e):(t==="avg"?r=new Yh(e,"avg"):(N(t==="max",()=>`Invalid pool type ${t}`),r=new Yh(e,"max")),i.push({type:"int32",data:[e.padInfo.top,e.padInfo.left]},{type:"int32",data:[e.dilationHeight,e.dilationWidth]},{type:"int32",data:[e.inHeight,e.inWidth]},{type:"int32",data:[e.effectiveFilterHeight,e.effectiveFilterWidth]})),s.runWebGPUProgram(r,[n],n.dtype,i)}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Gse(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{filterSize:i,strides:o,pad:a,dimRoundingMode:l}=s,u=Rs(r.shape,i,o,1,a,l);return yk(r,u,"avg",t)}const Hse={kernelName:rd,backendName:"webgpu",kernelFunc:Gse};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qse(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{filterSize:i,strides:o,pad:a,dataFormat:l,dimRoundingMode:c}=s,u=[1,1,1],h=$r(r.shape,i,o,u,a,c,l),d=new ib(h,"avg"),p=[{type:"int32",data:[h.strideDepth,h.strideHeight,h.strideWidth]},{type:"int32",data:[h.padInfo.front,h.padInfo.top,h.padInfo.left]},{type:"int32",data:[h.inDepth,h.inHeight,h.inWidth]},{type:"int32",data:[h.effectiveFilterDepth,h.effectiveFilterHeight,h.effectiveFilterWidth]}];return t.runWebGPUProgram(d,[r],r.dtype,p)}const Xse={kernelName:id,backendName:"webgpu",kernelFunc:qse};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Kse{constructor(e){this.variableNames=["dy"],this.uniforms=`strides : vec2, pads : vec2, dilations : vec2, filterDims : vec2, + outHeight : i32, outWidth : i32, avgMultiplier : f32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="avgPool2DBackprop"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords[0]; + let d = coords[3]; + + let dyRCCorner = vec2(coords.yz) - uniforms.pads; + let dyRCorner = dyRCCorner.x; + let dyCCorner = dyRCCorner.y; + + // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d). + // ? = to be determined. : = across all values in that axis. + var dotProd = 0.0; + for (var wR = 0; wR < uniforms.filterDims[0]; wR = wR + uniforms.dilations[0]) { + let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]); + + if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) { + continue; + } + let idyR = i32(dyR); + + for (var wC = 0; wC < uniforms.filterDims[1]; wC = wC + uniforms.dilations[1]) { + let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]); + + if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) { + continue; + } + let idyC = i32(dyC); + + let dyValue = getDy(batch, idyR, idyC, d); + + dotProd = dotProd + dyValue * uniforms.avgMultiplier; + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}class jse{constructor(e){this.variableNames=["dy"],this.uniforms=`strides : vec3, pads : vec3, filterDims : vec3, + outDepth : i32, outHeight : i32, outWidth : i32, avgMultiplier : f32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="avgPool3DBackprop"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords.x; + let ch = coords.u; + + let dyCorner = vec3(coords.y, coords.z, coords.w) - uniforms.pads; + let dyDCorner = dyCorner.x; + let dyRCorner = dyCorner.y; + let dyCCorner = dyCorner.z; + + // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get + // dx(xD, xR, xC, ch). + // ? = to be determined. : = across all values in that axis. + var dotProd = 0.0; + for (var wD = 0; wD < uniforms.filterDims[0]; wD++) { + let dyD = f32(dyDCorner + wD) / f32(uniforms.strides[0]); + + if (dyD < 0.0 || dyD >= f32(uniforms.outDepth) || fract(dyD) > 0.0) { + continue; + } + let idyD = i32(dyD); + + for (var wR = 0; wR < uniforms.filterDims[1]; wR++) { + let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]); + + if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) { + continue; + } + let idyR = i32(dyR); + + for (var wC = 0; wC < uniforms.filterDims[2]; wC++) { + let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]); + + if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) { + continue; + } + let idyC = i32(dyC); + + let dyValue = getDy(batch, idyD, idyR, idyC, ch); + dotProd += dyValue * uniforms.avgMultiplier; + } + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Yse(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:i}=e,o=i,{filterSize:a,strides:l,pad:c,dimRoundingMode:u}=s,h=$r(o.shape,a,l,1,c,u),d=new jse(h),p=1/(h.filterDepth*h.filterHeight*h.filterWidth),f=[{type:"int32",data:[h.strideDepth,h.strideHeight,h.strideWidth]},{type:"int32",data:[h.effectiveFilterDepth-1-h.padInfo.front,h.effectiveFilterHeight-1-h.padInfo.top,h.effectiveFilterWidth-1-h.padInfo.left]},{type:"int32",data:[h.effectiveFilterDepth,h.effectiveFilterHeight,h.effectiveFilterWidth]},{type:"int32",data:[h.outDepth]},{type:"int32",data:[h.outHeight]},{type:"int32",data:[h.outWidth]},{type:"float32",data:[p]}];return t.runWebGPUProgram(d,[r],o.dtype,f)}const Zse={kernelName:T0,backendName:"webgpu",kernelFunc:Yse};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Jse(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:i}=e,o=i;fk([r,i],"avgPoolGrad");const{filterSize:a,strides:l,pad:c}=s,u=Rs(o.shape,a,l,1,c),h=new Kse(u),d=1/(u.filterHeight*u.filterWidth),p=[{type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.effectiveFilterHeight-1-u.padInfo.top,u.effectiveFilterWidth-1-u.padInfo.left]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[u.effectiveFilterHeight,u.effectiveFilterWidth]},{type:"int32",data:[u.outHeight]},{type:"int32",data:[u.outWidth]},{type:"float32",data:[d]}];return t.runWebGPUProgram(h,[r],o.dtype,p)}const Qse={kernelName:_0,backendName:"webgpu",kernelFunc:Jse};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ere(n){const{inputs:e,backend:t,attrs:s}=n,{a:r,b:i}=e,{transposeA:o,transposeB:a}=s;return ng({a:r,b:i,transposeA:o,transposeB:a,backend:t})}const tre={kernelName:od,backendName:"webgpu",kernelFunc:ere};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class nre{constructor(e,t){this.variableNames=["source"],this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.rank=t.length,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.start=e,this.uniforms=`start : ${zn(e.length)}, `,this.shaderKey="slice"}getUserCode(){const e=zn(this.rank),t=sre(this.rank);let s;return this.start.length===1?s=this.outputShape.map((i,o)=>"sourceLoc = uniforms.start + coords;"):s=this.outputShape.map((i,o)=>`sourceLoc.${Ex[o]} = uniforms.start.${Io(o)} + coords.${Ex[o]};`),` + ${De("index")} { + if (index < uniforms.size) { + var sourceLoc : ${e}; + let coords = getCoordsFromIndex(index); + ${s.join(` +`)} + setOutputAtIndex(index, getSource(${t})); + } + } + `}}const Ex=["x","y","z","w","u","v"];function sre(n){if(n===1)return"sourceLoc";if(n<=6)return Ex.slice(0,n).map(e=>`sourceLoc.${e}`).join(",");throw Error(`Slicing for rank ${n} is not yet supported`)}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ih(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{begin:i,size:o}=s,[a,l]=vm(r,i,o);if(hv(r,a,l),t.shouldExecuteOnCPU([r])||r.dtype==="string"){const h=t.tensorMap.get(r.dataId),d=ese(h.values,a,l,r.shape,r.dtype);return t.makeTensorInfo(l,r.dtype,d)}if(re(l)===0)return t.makeTensorInfo(l,r.dtype,[]);const c=new nre(a,l),u=[{type:"int32",data:a}];return t.runWebGPUProgram(c,[r],r.dtype,u)}const rre={kernelName:Xd,backendName:"webgpu",kernelFunc:ih};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ire=n=>{const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{blockShape:i,crops:o}=s;N(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGPU backend not implemented yet");const a=i.reduce((v,b)=>v*b),l=Dl(r.shape,i,a),c=Pl(l.length,i.length),u=Ll(r.shape,i,a),h=Sm(o,i.length),d=Cm(u,o,i.length),p=[],f=tt({inputs:{x:r},backend:t,attrs:{shape:l}}),x=to({inputs:{x:f},backend:t,attrs:{perm:c}}),m=tt({inputs:{x},backend:t,attrs:{shape:u}}),g=ih({inputs:{x:m},backend:t,attrs:{begin:h,size:d}});return p.push(f),p.push(x),p.push(m),p.forEach(v=>t.disposeData(v.dataId)),g},ore={kernelName:ad,backendName:"webgpu",kernelFunc:ire};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const are=` + fn bincount_write(index: i32, value: f32) { + ${Aa("&result[index]","value","float32")} + } +`,lre=` + fn bincount_write(index: i32, value: f32) { + atomicStore(&result[index], bitcast(value)); + } +`;class wk{constructor(e,t,s=!1){this.outputShape=[],this.variableNames=["x"],this.uniforms="binCountSize : i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.hasWeights=!0,this.binaryOutput=!1,this.outputShape=e,this.rank=e.length,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.binaryOutput=s,s&&(this.atomic=!1),this.hasWeights=t,this.hasWeights&&this.variableNames.push("w"),this.shaderKey=`bincount_${this.hasWeights}_${this.binaryOutput}_${this.rank}`}getUserCode(){return` + ${this.binaryOutput?lre:are} + ${De("index")} { + ${this.rank===1?`if (index < uniforms.xShape) { + let indexVal = i32(getX(index)); + if (indexVal < uniforms.binCountSize) { + let value = ${this.binaryOutput?1:this.hasWeights?"getW(index)":"1."}; + bincount_write(indexVal, value); + } + }`:`let coord = getCoordsFromIndex(index); + if (coordsInBounds2D(coord, uniforms.xShape)) { + let indexVal = i32(getX(coord[0], coord[1])); + if (indexVal < uniforms.binCountSize) { + let value = ${this.binaryOutput?1:this.hasWeights?"getW(coord[0], coord[1])":"1."}; + bincount_write(coord.x * uniforms.binCountSize + indexVal, value); + } + }`} + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cre(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,weights:i}=e,{size:o}=s,a=re(r.shape),c=re(i.shape)>0,u=[o],h=i.dtype,d=sr({backend:t,attrs:{shape:u,value:0,dtype:h}}),p=new wk([a],c),f=[{type:"int32",data:[o]}],x=c?[r,i]:[r];return t.runWebGPUProgram(p,x,h,f,d)}const ure={kernelName:I0,backendName:"webgpu",kernelFunc:cre};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class hre{constructor(e){this.outputShape=[],this.variableNames=["s0","s1"],this.uniforms="s0Size : i32, s1Size : i32, ",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="broadcastArgs"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + var s0 = 1.0; + var s1 = 1.0; + let indexS0 = index - uniforms.size + uniforms.s0Size; + let indexS1 = index - uniforms.size + uniforms.s1Size; + if (indexS0 >= 0) { + s0 = getS0(indexS0); + } + if (indexS1 >= 0) { + s1 = getS1(indexS1); + } + + if (s0 == 1.0) { + setOutputAtIndex(index, s1); + } else if (s1 == 1.0) { + setOutputAtIndex(index, s0); + } else if (s0 != s1) { + setOutputAtIndex(index, uniforms.NAN); + } else { + setOutputAtIndex(index, s0); + } + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function dre(n){const{inputs:e,backend:t}=n,{s0:s,s1:r}=e;if(t.shouldExecuteOnCPU([s,r])){const u=t.tensorMap.get(s.dataId),h=t.tensorMap.get(r.dataId),d=u.values,p=h.values,f=pt(Array.from(d),Array.from(p));return t.makeTensorInfo([f.length],"int32",Int32Array.from(f))}const i=re(s.shape),o=re(r.shape),a=Math.max(i,o),l=new hre(a),c=[{type:"int32",data:[i]},{type:"int32",data:[o]}];return t.runWebGPUProgram(l,[s,r],"int32",c)}const pre={kernelName:u2,backendName:"webgpu",kernelFunc:dre};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Sk=xs({opType:bt.NOT_EQUAL,dtype:"bool",cpuKernelImpl:Kne}),fre={kernelName:Pd,backendName:"webgpu",kernelFunc:Sk};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wp(n){const{inputs:e,backend:t}=n,{input:s}=e,r=t.tensorMap.get(s.dataId);return br({inputs:{x:r.complexTensorInfos.real},backend:t})}const mre={kernelName:Y0,backendName:"webgpu",kernelFunc:wp};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gre(n,e){const t=new rh(n.shape,Me.TO_INT),s=e.runWebGPUProgram(t,[n],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kx(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{dtype:i}=s;if(i==="complex64"){if(r.dtype==="complex64")return br({inputs:{x:r},backend:t});const o=On(r.shape),a=kx({inputs:{x:r},backend:t,attrs:{dtype:"float32"}}),l=Gl({inputs:{real:a,imag:o},backend:t});return o.dispose(),t.disposeData(a.dataId),l}if(r.dtype==="complex64"){const o=wp({inputs:{input:r},backend:t}),a=kx({inputs:{x:o},backend:t,attrs:{dtype:i}});return t.disposeData(o.dataId),a}if(!i2(r.dtype,i)){const o=br({inputs:{x:r},backend:t});return{dataId:o.dataId,shape:o.shape,dtype:i}}if(t.shouldExecuteOnCPU([r])){const o=t.tensorMap.get(r.dataId).values,[a,l,c]=kne(o,r.shape,r.dtype,i);return t.makeTensorInfo(a,l,c)}if(i==="int32")return gre(r,t);if(i==="bool"){const o=t.makeTensorInfo([],"bool",hs("bool",1)),l=Sk({inputs:{a:r,b:o},backend:t});return t.disposeData(o.dataId),l}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${i}`)}const xre={kernelName:su,backendName:"webgpu",kernelFunc:kx};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vre=jt({opType:Me.CEIL,cpuKernelImpl:Ane}),bre={kernelName:ru,backendName:"webgpu",kernelFunc:vre};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class yre{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32, maxVal : f32,",this.workPerThread=4,this.workgroupSize=[64,1,1],this.outputComponent=4,this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.shaderKey="clipVec4"}getUserCode(){return` + ${De("index")} { + if(index < uniforms.size) { + let value = getAByOutputIndex(index); + var clampedValue = clamp( + value, vec4(uniforms.minVal), vec4(uniforms.maxVal)); + clampedValue = select(clampedValue, value, isnanVec4(value)); + setOutputAtIndex(index, clampedValue); + } + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class wre{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32, maxVal : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="clip"}getUserCode(){return` + ${De("index")} { + if(index < uniforms.size) { + let value = getAByOutputIndex(index); + if (isnan(value)) { + setOutputAtIndex(index, value); + return; + } + setOutputAtIndex(index, clamp(value, uniforms.minVal, uniforms.maxVal)); + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Sre(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{clipValueMin:i,clipValueMax:o}=s;let a;const l=[{type:"float32",data:[i]},{type:"float32",data:[o]}];return re(r.shape)%4===0?a=new yre(r.shape):a=new wre(r.shape),t.runWebGPUProgram(a,[r],r.dtype,l)}const Cre={kernelName:iu,backendName:"webgpu",kernelFunc:Sre};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class _re{constructor(e){this.outputShape=[],this.variableNames=["real","imag"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="complexAbs"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let re = abs(getRealByOutputIndex(index)); + let im = abs(getImagByOutputIndex(index)); + let mx = max(re, im); + + // The length function in wgsl may be not underflow-safe on some GPUs. + // So the safe solution is to ensure underflow-safety in all cases. + setOutputAtIndex(index, select(mx * length(vec2(1, min(re, im)/mx)), 0.0, mx == 0.0)); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $w(n,e){return{dataId:e.dataId,dtype:e.dtype,shape:n.shape}}function Tre(n){const{inputs:e,backend:t}=n,{x:s}=e,r=t.tensorMap.get(s.dataId),i=new _re(s.shape),o=[$w(s,r.complexTensorInfos.real),$w(s,r.complexTensorInfos.imag)];return t.runWebGPUProgram(i,o,o[0].dtype)}const Ire={kernelName:ld,backendName:"webgpu",kernelFunc:Tre};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ere{constructor(e){this.uniforms="",this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=nr(e,1),this.variableNames=e.map((t,s)=>`T${s}`),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.offsetLength=e.length-1;for(let t=0;t0){e.push("if (yC < uniforms.offset0){ setOutputAtCoords(coords.x, coords.y, getT0(yR, yC)); }");for(let i=1;iwp({inputs:{input:b},backend:t})),x=n.map(b=>sg({inputs:{input:b},backend:t})),m=Ah(f,e,t),g=Ah(x,e,t),v=Gl({inputs:{real:m,imag:g},backend:t});return f.forEach(b=>t.disposeData(b.dataId)),x.forEach(b=>t.disposeData(b.dataId)),t.disposeData(m.dataId),t.disposeData(g.dataId),v}let r=t.shouldExecuteOnCPU(n);if(s==="string"&&(r=!0),r){const f=n.map(w=>{const T=[-1,re(w.shape.slice(e))];return tt({inputs:{x:w},backend:t,attrs:{shape:T}})}),x=f.map(w=>({vals:t.readSync(w.dataId),shape:w.shape})),m=nr(f.map(w=>w.shape),1),g=f[0].shape[0]===1,v=Rne(x,m,s,g),b=nr(n.map(w=>w.shape),e),y=t.makeTensorInfo(b,s,v);return f.forEach(w=>t.disposeData(w.dataId)),y}const i=t.device.limits.maxStorageBuffersPerShaderStage-1;if(n.length>i){const f=[];for(let m=0;mf.shape),c=new Ere(l),u=[],h=new Array(l.length-1);if(h.length>0){h[0]=l[0][1],u.push({type:"int32",data:[h[0]]});for(let f=1;ft.disposeData(f.dataId));const p=tt({inputs:{x:d},backend:t,attrs:{shape:a}});return t.disposeData(d.dataId),p}function Are(n,e,t){const s=nr(n.map(i=>i.shape),e);return{tensors2D:n.map(i=>tt({inputs:{x:i},backend:t,attrs:{shape:[re(i.shape.slice(0,e)),re(i.shape.slice(e))]}})),outShape:s}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ck(n){const{inputs:e,backend:t,attrs:s}=n,{axis:r}=s,i=It(r,e[0].shape)[0],o=e.map(c=>c.shape);bm(o,i);const a=nr(e.map(c=>c.shape),i);if(re(a)===0)return t.makeTensorInfo(a,e[0].dtype,[]);const l=e.filter(c=>re(c.shape)>0);return l.length===1?br({inputs:{x:l[0]},backend:t}):Ah(l,i,t)}const Rre={kernelName:cd,backendName:"webgpu",kernelFunc:Ck};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Mre(n,e,t,s,r=!1,i=null,o=!1,a=4,l=4,c=4){const u=R=>{switch(R){case 1:return"resData = f32(x[xIndex]);";case 3:return"resData = vec3(x[xIndex], x[xIndex + 1], x[xIndex + 2]);";case 4:return"resData = vec4(x[xIndex / 4]);";default:throw new Error(`innerElementSize ${R} is not supported.`)}},h=R=>{switch(R){case 1:return"return f32(W[row * uniforms.wShape[3] + col]);";case 4:return"return vec4(W[(row * uniforms.wShape[3] + col) / 4]);";default:throw new Error(`innerElementSize ${R} is not supported.`)}},d=n?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,p=n?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,f=n?"uniforms.xShape[1]":"uniforms.xShape[2]",x=n?"uniforms.xShape[2]":"uniforms.xShape[3]",m=n?"row":"col",g=n?"col":"row",v=` + let inChannels = uniforms.wShape[2]; + let outWidth = ${n?"uniforms.outShape[2]":"uniforms.outShape[3]"}; + let outRow = ${m} / outWidth; + let outCol = ${m} % outWidth; + + let WRow = ${g} / (uniforms.filterDims[1] * inChannels); + let WCol = ${g} / inChannels % uniforms.filterDims[1]; + let xRow = outRow * uniforms.strides[0] + uniforms.dilations[0] * WRow - uniforms.pads[0]; + let xCol = outCol * uniforms.strides[1] + uniforms.dilations[1] * WCol - uniforms.pads[1]; + let xCh = ${g} % inChannels; + var resData = ${Rt(a)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${f} && xCol >= 0 && xCol < ${x}) { + ${d} + let xIndex = getIndexFromCoords4D(coord, uniforms.xShape); + ${u(a)} + } + return resData;`,b=n?e&&s?` + ${v}`:` + if (row < uniforms.dimAOuter && col < uniforms.dimInner) { + ${v} + } + return ${Rt(a)}(0.0);`:s&&t?` + ${v}`:` + if (row < uniforms.dimInner && col < uniforms.dimBOuter) { + ${v} + } + return ${Rt(a)}(0.0);`,y=`${h(l)}`,w=Rt(c),C=Rt(n?a:l),T=Rt(n?l:a);return` + ${Do(i,o,c===4,4)} + fn mm_readA(batch: i32, row : i32, col : i32) -> ${C} { + ${n?b:y} + } + + fn mm_readB(batch: i32, row : i32, col : i32) -> ${T} { + ${n?y:b} + } + + fn mm_write(batch: i32, row : i32, col : i32, valueIn : ${w}) { + if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) + { + var value = valueIn; + let outWidth = ${n?"uniforms.outShape[2]":"uniforms.outShape[3]"}; + ${p} + ${Wl(r,i)} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`}class Nre{constructor(e,t,s,r,i=!1,o=null,a=!1,l=!1){this.variableNames=["x","W"],this.uniforms="filterDims : vec2, pads : vec2, strides : vec2, dilations : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.outputShape=e.outShape,this.isChannelsLast=e.dataFormat==="channelsLast",this.isVec4=((e.inChannels%4===0||e.inChannels%3===0)&&this.isChannelsLast||e.outWidth%4===0&&!this.isChannelsLast)&&e.outChannels%4===0,this.dispatchLayout=this.isChannelsLast?{x:[3],y:[1,2],z:[0]}:{x:[2,3],y:[1],z:[0]},this.workgroupSize=hk(this.dispatchLayout,this.outputShape,this.isVec4),this.elementsPerThread=dk(this.dispatchLayout,this.outputShape,this.isVec4),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread),this.isVec4?(this.outputComponent=4,this.isChannelsLast&&e.inChannels%4!==0?(this.innerElementSize=3,this.variableComponents=[1,4]):(this.innerElementSize=4,this.variableComponents=[4,4]),i&&(this.variableNames.push("bias"),this.variableComponents.push(4)),a&&(this.variableNames.push("preluActivationWeights"),this.variableComponents.push(4))):(this.innerElementSize=this.elementsPerThread[0],i&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights")),this.sequentialAccessByThreads=l,this.addBias=i,this.activation=o,this.hasPreluActivationWeights=a,this.tileAOuter=this.workgroupSize[1]*this.elementsPerThread[1],this.tileBOuter=this.workgroupSize[0]*this.elementsPerThread[0],this.tileInner=Math.max(this.workgroupSize[0]*this.innerElementSize,this.workgroupSize[1]),this.fitAOuter=t%this.tileAOuter===0,this.fitBOuter=s%this.tileBOuter===0,this.fitInner=r%this.tileInner===0,this.shaderKey=`conv2DMM_${this.elementsPerThread}_${this.activation}}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.innerElementSize}_${this.isChannelsLast}_${this.sequentialAccessByThreads}`}getUserCode(){const e=this.isVec4?eg(this.elementsPerThread,this.workgroupSize,!this.isChannelsLast,this.tileInner):tg(this.elementsPerThread,this.workgroupSize,!this.isChannelsLast,this.tileInner,!1,null,this.sequentialAccessByThreads),t=this.isVec4?[this.innerElementSize,4,4]:[1,1,1];return` + ${Mre(this.isChannelsLast,this.fitAOuter,this.fitBOuter,this.fitInner,this.addBias,this.activation,this.hasPreluActivationWeights,t[0],t[1],t[2])} + ${e} + `}}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class $re{constructor(e,t=!1,s=null,r=!1){this.variableNames=["x","W"],this.uniforms="filterDims: vec2, pads: vec2, strides: vec2, dilations: vec2,",this.workgroupSize=[4,4,8],this.outputShape=e.outShape,this.isChannelsLast=e.dataFormat==="channelsLast",this.dispatchLayout=this.isChannelsLast?{x:[2],y:[1],z:[0,3]}:{x:[3],y:[2],z:[0,1]},this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.addBias=t,this.activation=s,this.hasPreluActivationWeights=r,t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.shaderKey=`conv2dnaive_${this.activation}_${this.isChannelsLast}`}getUserCode(){return` + ${Do(this.activation,this.hasPreluActivationWeights,!1,4)} + fn readInp(batch : i32, row : i32, col : i32, chan : i32) -> f32{ + let coords = vec4(batch, row, col, chan); + if (coordsInBounds4D(coords, uniforms.xShape)) { + return getX(batch, row, col, chan); + } else { + return 0.0; + } + } + fn readFilt(row : i32, col : i32, xChannel : i32, outChannel : i32) -> f32{ + let coords = vec4(row, col, xChannel, outChannel); + if(coordsInBounds4D(coords, uniforms.wShape)) { + return getW(row, col, xChannel, outChannel); + } else { + return 0.0; + } + } + fn writeResult(batch : i32, row : i32, col : i32, chan : i32, valueIn : f32) { + let coords = ${this.isChannelsLast?"vec4(batch, row, col, chan);":"vec4(batch, chan, row, col);"} + if (coordsInBounds4D(coords, uniforms.outShape)) { + var value = valueIn; + ${Wl(this.addBias,this.activation)} + setOutputAtCoords(coords.x, coords.y, coords.z, coords.w, value); + } + } + ${De("index")} { + let coords = getOutputCoords(); + let batch = coords[0]; + let outChannel = ${this.isChannelsLast?"coords[3];":"coords[1];"} + let outRow = ${this.isChannelsLast?"coords[1];":"coords[2];"} + let outCol = ${this.isChannelsLast?"coords[2];":"coords[3];"} + var acc : f32 = 0.0; + for (var row = 0; row < uniforms.filterDims[0]; row = row + 1) { + for (var col = 0; col < uniforms.filterDims[1]; col = col + 1) { + let xRow = outRow * uniforms.strides[0] + uniforms.dilations[0] * row - uniforms.pads[0]; + let xCol = outCol * uniforms.strides[1] + uniforms.dilations[1] * col - uniforms.pads[1]; + for (var xChannel = 0; xChannel < ${this.isChannelsLast?"uniforms.xShape[3];":"uniforms.xShape[1];"} xChannel = xChannel + 1) { + ${this.isChannelsLast?"let v = readInp(batch, xRow, xCol, xChannel);":"let v = readInp(batch, xChannel, xRow, xCol);"} + let f = readFilt(row, col, xChannel, outChannel); + acc = acc + v * f; + } + } + } + writeResult(batch, outRow, outCol, outChannel, acc); + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Dre{constructor(e,t){this.variableNames=["x"],this.uniforms=`pads : vec2, strides : vec2, dilations : vec2, outWidth : i32, itemsPerBlockRow : i32, + inChannels : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.isChannelsLast=t,this.shaderKey=`im2col_${this.isChannelsLast}`}getUserCode(){const e=this.isChannelsLast?1:2,t=this.isChannelsLast?2:3,s=this.isChannelsLast?"coords[1]":"coords[2]",r=this.isChannelsLast?"coords[2]":"coords[1]",i=this.isChannelsLast?"getX(batch, xRow, xCol, ch)":"getX(batch, ch, xRow, xCol)";return` + ${De("index")} { + let coords = getCoordsFromIndex(index); + if(index < uniforms.size) { + let batch = coords[0]; + let row = ${s}; + let col = ${r}; + let offsetY = (row / uniforms.outWidth) * uniforms.strides[0] - uniforms.pads[0]; + let xRow = offsetY + uniforms.dilations[0] * (col / uniforms.itemsPerBlockRow); + var value = 0.0; + if(xRow < uniforms.xShape[${e}] && xRow >= 0) { + let offsetX = (row % uniforms.outWidth) * uniforms.strides[1] - + uniforms.pads[1]; + let xCol = offsetX + uniforms.dilations[1] * ((col % + uniforms.itemsPerBlockRow) / uniforms.inChannels); + let ch = col % uniforms.inChannels; + if(xCol < uniforms.xShape[${t}] && xCol >= 0) { + value = ${i}; + } + } + setOutputAtIndex(index, value); + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function i0(n,e){const t=n.length;return t>=3?e?[...n.slice(0,-3),n[t-3]*n[t-2],n[t-1]]:[...n.slice(0,-3),n[t-3],n[t-2]*n[t-1]]:!e&&t===1&&n[0]>1?[n[0],1]:null}function Pre({x:n,filter:e,convInfo:t,backend:s,bias:r=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:a=null}){const l=t.dataFormat==="channelsLast",c=!l,u=!1,h=l&&t.filterHeight===t.inHeight&&t.filterWidth===t.inWidth&&t.padInfo.type==="VALID",d=[];let p,f;if(h){const g=t.inHeight*t.inWidth*t.inChannels;p=tt({inputs:{x:n},backend:s,attrs:{shape:[1,t.batchSize,g]}}),f=tt({inputs:{x:e},backend:s,attrs:{shape:[1,g,t.outChannels]}})}else p=tt({inputs:{x:n},backend:s,attrs:{shape:l?[t.batchSize,t.inHeight*t.inWidth,t.inChannels]:[t.batchSize,t.inChannels,t.inHeight*t.inWidth]}}),f=tt({inputs:{x:e},backend:s,attrs:{shape:[1,t.inChannels,t.outChannels]}});if(d.push(p),d.push(f),i!=null){const g=i0(i.shape,l);g!=null&&(i=tt({inputs:{x:i},backend:s,attrs:{shape:g}}),d.push(i))}if(r!=null){const g=i0(r.shape,l);g!=null&&(r=tt({inputs:{x:r},backend:s,attrs:{shape:g}}),d.push(r))}const x=ng({a:l?p:f,b:l?f:p,transposeA:c,transposeB:u,backend:s,bias:r,activation:a,preluActivationWeights:i,leakyreluAlpha:o}),m=tt({inputs:{x},backend:s,attrs:{shape:t.outShape}});d.push(x);for(const g of d)s.disposeData(g.dataId);return m}function Lre({x:n,filter:e,convInfo:t,backend:s,bias:r=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:a=null}){const{filterWidth:l,filterHeight:c,inChannels:u,strideWidth:h,strideHeight:d,padInfo:p,outWidth:f,outHeight:x,dilationWidth:m,dilationHeight:g,dataFormat:v}=t,b=v==="channelsLast",y=l*c*u,w=x*f,C=b?[t.batchSize,w,y]:[t.batchSize,y,w],T=new Dre(C,b),E=[{type:"int32",data:[p.top,p.left]},{type:"int32",data:[d,h]},{type:"int32",data:[g,m]},{type:"int32",data:[f]},{type:"int32",data:[u*l]},{type:"int32",data:[u]}],R=s.runWebGPUProgram(T,[n],n.dtype,E),_=[];_.push(R);const k=tt({inputs:{x:e},backend:s,attrs:{shape:[1,y,-1]}});if(_.push(k),i!=null){const L=i0(i.shape,b);L!=null&&(i=tt({inputs:{x:i},backend:s,attrs:{shape:L}}),_.push(i))}if(r!=null){const L=i0(r.shape,b);L!=null&&(r=tt({inputs:{x:r},backend:s,attrs:{shape:L}}),_.push(r))}const M=ng({a:b?R:k,b:b?k:R,transposeA:!b,transposeB:!1,backend:s,bias:r,activation:a,preluActivationWeights:i,leakyreluAlpha:o}),P=tt({inputs:{x:M},backend:s,attrs:{shape:t.outShape}});_.push(M);for(const L of _)s.disposeData(L.dataId);return P}function _k({x:n,filter:e,convInfo:t,backend:s,bias:r=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:a=null}){const l=r!=null,c=i!=null,u=t.dataFormat==="channelsLast",h=u&&t.filterHeight===t.inHeight&&t.filterWidth===t.inWidth&&t.padInfo.type==="VALID",d=oe().getBool("WEBGPU_USE_NAIVE_CONV2D_DEBUG");if(!d&&(h||t.filterHeight===1&&t.filterWidth===1&&t.dilationHeight===1&&t.dilationWidth===1&&t.strideHeight===1&&t.strideWidth===1&&(t.padInfo.type==="SAME"||t.padInfo.type==="VALID")))return Pre({x:n,filter:e,convInfo:t,backend:s,bias:r,activation:a,preluActivationWeights:i,leakyreluAlpha:o});const p=oe().getNumber("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL"),f=p>-1?p:s.thresholdToIncreaseWorkgroups,x=t.batchSize*Math.ceil(t.outHeight*t.outWidth/32)*Math.ceil(t.outChannels/32);if(oe().getBool("WEBGPU_CONV_SEPARATE_IM2COL_SHADER")||x<=f)return Lre({x:n,filter:e,convInfo:t,backend:s,bias:r,preluActivationWeights:i,leakyreluAlpha:o,activation:a});let m;const g=[t.padInfo.top,t.padInfo.left],v=[{type:"int32",data:[t.filterHeight,t.filterWidth]},{type:"int32",data:[...g]},{type:"int32",data:[t.strideHeight,t.strideWidth]},{type:"int32",data:[t.dilationHeight,t.dilationWidth]}];if(d)m=new $re(t,l,a,c);else{const C=u?t.outHeight*t.outWidth:t.outChannels,T=u?t.outChannels:t.outHeight*t.outWidth,E=t.filterHeight*t.filterWidth*t.inChannels;v.push({type:"int32",data:[C]},{type:"int32",data:[T]},{type:"int32",data:[E]});const R=s.adapterInfo.isIntel();m=new Nre(t,C,T,E,l,a,c,R)}const b=[],y=[n,e];l&&(!u&&r.shape.length===1&&(r=tt({inputs:{x:r},backend:s,attrs:{shape:[r.shape[0],1,1]}}),b.push(r)),y.push(r)),c&&(!u&&i.shape.length===1&&(i=tt({inputs:{x:i},backend:s,attrs:{shape:[i.shape[0],1,1]}}),b.push(i)),y.push(i)),a==="leakyrelu"&&(v.push({type:"float32",data:[o]}),m.uniforms+=" alpha : f32,");const w=s.runWebGPUProgram(m,y,n.dtype,v);for(const C of b)s.disposeData(C.dataId);return w}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Fre(n){const{inputs:e,attrs:t,backend:s}=n,{x:r,filter:i}=e,{strides:o,pad:a,dataFormat:l,dilations:c,dimRoundingMode:u}=t,h=wr(l),d=Cn(r.shape,i.shape,o,c,a,u,!1,h);return _k({x:r,filter:i,convInfo:d,backend:s})}const Ore={kernelName:ud,backendName:"webgpu",kernelFunc:Fre};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class zre{constructor(e){this.variableNames=["dy","W"],this.uniforms="filterDims : vec2, pads : vec2, strides : vec2, outBackprop : vec4,",this.workgroupSize=[64,1,1],this.size=!1,this.isVec4=!1,this.workPerThread=1,this.outputShape=e.inShape,this.isChannelsLast=e.dataFormat==="channelsLast",this.isVec4=this.isChannelsLast&&e.outChannels%4===0&&e.inChannels%4===0,this.isVec4?(this.workPerThread=2,this.outputComponent=4,this.workgroupSize=[4,4,4],this.dispatchLayout={x:[3],y:[2],z:[0,1]},this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize,[4,this.workPerThread,1])):(this.size=!0,this.workPerThread=1,this.workgroupSize=[64,1,1],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize)),this.shaderKey=`conv2DDerInput_${this.isChannelsLast}_${this.isVec4}_${this.workPerThread}`}getUserCode(){const e=this.isChannelsLast?1:2,t=this.isChannelsLast?2:3,s=this.isChannelsLast?3:1,r=` + ${De()} { + let batch = i32(globalId.z) / uniforms.outShape[1]; + let r = i32(globalId.z) % uniforms.outShape[1]; + let c = i32(globalId.y) * ${this.workPerThread}; + let d1 = i32(globalId.x) * 4; + + let dyCorner = vec2(r, c) - uniforms.pads; + + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd: array, ${this.workPerThread}>; + for (var i = 0; i < ${this.workPerThread}; i++) { + dotProd[i] = vec4(0.0); + } + for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) { + let dyR = f32(dyCorner.x + wR) / f32(uniforms.strides.x); + let wRPerm = uniforms.filterDims.x - 1 - wR; + if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) || + fract(dyR) > 0.0) { + continue; + } + let idyR = i32(dyR); + + for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + 1) { + let dyC = f32(dyCorner.y + wC) / f32(uniforms.strides.y); + let dyC2 = f32(dyCorner.y + 1 + wC) / f32(uniforms.strides.y); + let wCPerm = uniforms.filterDims.y - 1 - wC; + var bDyCVal = true; + var bDyCVal2 = true; + if (dyC < 0.0 || dyC >= f32(uniforms.outBackprop[2]) || + fract(dyC) > 0.0) { + bDyCVal = false; + } + if (dyC2 < 0.0 || dyC2 >= f32(uniforms.outBackprop[2]) || + fract(dyC2) > 0.0) { + bDyCVal2 = false; + } + + let idyC = i32(dyC); + let idyC2 = i32(dyC2); + if (bDyCVal && bDyCVal2) { + let d2Length = uniforms.outBackprop[3]; + for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = getW(wRPerm, wCPerm, d1, d2); + let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2); + let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2); + let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2); + var xValue = getDy(batch, idyR, idyC, d2); + let tmpval = vec4(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + xValue = getDy(batch, idyR, idyC2, d2); + dotProd[1] = dotProd[1] + vec4(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + } + } else if (bDyCVal) { + let d2Length = uniforms.outBackprop[3]; + for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = getW(wRPerm, wCPerm, d1, d2); + let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2); + let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2); + let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2); + var xValue = getDy(batch, idyR, idyC, d2); + let tmpval = vec4(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + } + } else if (bDyCVal2) { + let d2Length = uniforms.outBackprop[3]; + for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = getW(wRPerm, wCPerm, d1, d2); + let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2); + let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2); + let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2); + var xValue = getDy(batch, idyR, idyC2, d2); + let tmpval = vec4(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[1] = dotProd[1] + tmpval; + } + } + } + } + + for (var i = 0; i < ${this.workPerThread}; i = i + 1) { + let coords = vec4(batch, r, c + i, d1); + if (coordsInBounds4D(coords, uniforms.outShape)) { + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], dotProd[i]); + } + } + } + `;return this.isVec4?` + ${r} + `:` + ${De("index")} { + if(index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords[0]; + let d1 = coords[${s}]; + + let dyCorner = vec2(coords[${e}], coords[${t}]) - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd = 0.0; + for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) { + let dyR = (f32(dyRCorner) + f32(wR)) / f32(uniforms.strides.x); + let wRPerm = uniforms.filterDims.x - 1 - wR; + if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR = i32(dyR); + + for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + 1) { + let dyC = (f32(dyCCorner) + f32(wC)) / f32(uniforms.strides.y); + let wCPerm = uniforms.filterDims.y - 1 - wC; + if (dyC < 0.0 || dyC >= f32(uniforms.outBackprop[2]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC = i32(dyC); + + for (var d2 = 0; d2 < uniforms.outBackprop[3]; d2 = d2 + 1) { + let xValue = ${this.isChannelsLast?"getDy(batch, idyR, idyC, d2)":"getDy(batch, d2, idyR, idyC)"}; + let wValue = getW(wRPerm, wCPerm, d1, d2); + dotProd = dotProd + xValue * wValue; + } + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}class Bre{constructor(e){this.variableNames=["x","dy"],this.uniforms="pads : vec2, strides : vec2, batchSize : i32, outHeight : i32, outWidth : i32, inHeight : i32, inWidth : i32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.filterShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.isChannelsLast=e.dataFormat==="channelsLast",this.shaderKey=`conv2DDerFilter_${this.isChannelsLast}`}getUserCode(){return` + ${De("index")} { + if(index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let wR = coords[0]; + let wC = coords[1]; + let d1 = coords[2]; + let d2 = coords[3]; + + // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2). + // ? = to be determined. : = across all values in that axis. + var dotProd = 0.0; + for (var b = 0; b < uniforms.batchSize; b = b + 1) { + for (var yR = 0; yR < uniforms.outHeight; yR = yR + 1) { + let xR = wR + yR * uniforms.strides[0] - uniforms.pads[0]; + if (xR < 0 || xR >= uniforms.inHeight) { + continue; + } + + for (var yC = 0; yC < uniforms.outWidth; yC = yC + 1) { + let xC = wC + yC * uniforms.strides[1] - uniforms.pads[1]; + + if (xC < 0 || xC >= uniforms.inWidth) { + continue; + } + + if (${this.isChannelsLast}) { + let dyValue = getDy(b, yR, yC, d2); + let xValue = getX(b, xR, xC, d1); + dotProd = dotProd + xValue * dyValue; + } else { + let dyValue = getDy(b, d2, yR, yC); + let xValue = getX(b, d1, xR, xC); + dotProd = dotProd + xValue * dyValue; + } + } + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}class Ure{constructor(e){this.variableNames=["x","dy"],this.uniforms=`pads : vec3, strides : vec3, batchSize : i32, outDepth : i32, + outHeight : i32, outWidth : i32, inDepth : i32, inHeight : i32, inWidth : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.filterShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="conv3DDerFilter"}getUserCode(){return` + ${De("index")} { + if(index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let wF = coords.x; + let wR = coords.y; + let wC = coords.z; + let d1 = coords.w; + let d2 = coords.u; + + var dotProd = 0.0; + for (var b = 0; b < uniforms.batchSize; b++) { + for (var yF = 0; yF < uniforms.outDepth; yF++) { + let xF = wF + yF * uniforms.strides[0] - uniforms.pads[0]; + if (xF < 0 || xF >= uniforms.inDepth) { + continue; + } + + for (var yR = 0; yR < uniforms.outHeight; yR++) { + let xR = wR + yR * uniforms.strides[1] - uniforms.pads[1]; + if (xR < 0 || xR >= uniforms.inHeight) { + continue; + } + + for (var yC = 0; yC < uniforms.outWidth; yC++) { + let xC = wC + yC * uniforms.strides[2] - uniforms.pads[2]; + if (xC < 0 || xC >= uniforms.inWidth) { + continue; + } + + let dyValue = getDy(b, yF, yR, yC, d2); + let xValue = getX(b, xF, xR, xC, d1); + dotProd += xValue * dyValue; + } + } + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}class Vre{constructor(e){this.variableNames=["dy","W"],this.uniforms=`filterDims : vec3, pads : vec3, strides : vec3, + outDepth : i32, outHeight : i32, outWidth : i32, outChannels : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="conv3DDerInput"}getUserCode(){return` + ${De("index")} { + if(index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords.x; + let d1 = coords.u; + + let dyCorner = vec3(coords.y, coords.z, coords.w) - uniforms.pads; + let dyFCorner = dyCorner.x; + let dyRCorner = dyCorner.y; + let dyCCorner = dyCorner.z; + + var dotProd = 0.0; + for (var wF = 0; wF < uniforms.filterDims[0]; wF++) { + let dyF = f32(dyFCorner + wF) / f32(uniforms.strides[0]); + if (dyF < 0.0 || dyF >= f32(uniforms.outDepth) || fract(dyF) > 0.0) { + continue; + } + let idyF = i32(dyF); + + let wFPerm = uniforms.filterDims[0] - 1 - wF; + + for (var wR = 0; wR < uniforms.filterDims[1]; wR++) { + let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]); + + if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) { + continue; + } + let idyR = i32(dyR); + + let wRPerm = uniforms.filterDims[1] - 1 - wR; + + for (var wC = 0; wC < uniforms.filterDims[2]; wC++) { + let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]); + + if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) { + continue; + } + let idyC = i32(dyC); + + let wCPerm = uniforms.filterDims[2] - 1 - wC; + + for (var d2 = 0; d2 < uniforms.outChannels; d2++) { + let xValue = getDy(batch, idyF, idyR, idyC, d2); + let wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } + } + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Wre(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,dy:i}=e,{strides:o,pad:a,dataFormat:l,dimRoundingMode:c,filterShape:u}=s,h=wr(l),d=Cn(r.shape,u,o,1,a,c,!1,h),p=new Bre(d),f=[{type:"int32",data:[d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.batchSize]},{type:"int32",data:[d.outHeight]},{type:"int32",data:[d.outWidth]},{type:"int32",data:[d.inHeight]},{type:"int32",data:[d.inWidth]}];return t.runWebGPUProgram(p,[r,i],r.dtype,f)}const Gre={kernelName:k0,backendName:"webgpu",kernelFunc:Wre};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Hre(n=4){const e=i=>{switch(i){case 1:return"return W[getIndexFromCoords4D(coord, uniforms.wShape)];";case 4:return` + let coord1 = vec4(coordX, coordY, col + 1, rowInner); + let coord2 = vec4(coordX, coordY, col + 2, rowInner); + let coord3 = vec4(coordX, coordY, col + 3, rowInner); + let v0 = W[getIndexFromCoords4D(coord, uniforms.wShape)]; + let v1 = W[getIndexFromCoords4D(coord1, uniforms.wShape)]; + let v2 = W[getIndexFromCoords4D(coord2, uniforms.wShape)]; + let v3 = W[getIndexFromCoords4D(coord3, uniforms.wShape)]; + return vec4(v0, v1, v2, v3); + `;default:throw new Error(`innerElementSize ${i} is not supported.`)}},s=`if (row < uniforms.dimAOuter && col < uniforms.dimInner) { + ${` + let outRow = row / uniforms.outShape[2]; + let outCol = row % uniforms.outShape[2]; + + let WRow = col / (uniforms.filterDims[1] * uniforms.outBackprop[3]); + let WCol = col / uniforms.outBackprop[3] % uniforms.filterDims[1]; + let xR = f32(outRow - uniforms.pads[0] + WRow) / f32(uniforms.strides[0]); + let xC = f32(outCol - uniforms.pads[1] + WCol) / f32(uniforms.strides[1]); + if (xR < 0.0 || xR >= f32(uniforms.outBackprop[1]) || fract(xR) > 0.0) { + return ${Rt(n)}(0.0); + } + if (xC < 0.0 || xC >= f32(uniforms.outBackprop[2]) || fract(xC) > 0.0) { + return ${Rt(n)}(0.0); + } + let coord = vec4( + batch, + i32(xR), + i32(xC), + col % uniforms.outBackprop[3]); + return x[getIndexFromCoords4D(coord, uniforms.xShape)/${n}];`} + } + return ${Rt(n)}(0.0);`;return` + fn mm_readA(batch: i32, row : i32, col : i32) -> ${Rt(n)} { + ${s} + } + + fn mm_readB(batch: i32, row : i32, col : i32) -> ${Rt(n)} { + let coordX = uniforms.filterDims.x - 1 - + row / (uniforms.filterDims[1] * uniforms.outBackprop[3]); + let coordY = uniforms.filterDims.y - 1 - + (row / uniforms.outBackprop[3]) % uniforms.filterDims[1]; + if (row < uniforms.dimInner && col < uniforms.dimBOuter && + coordX >= 0 && coordY >= 0) { + let rowInner = row % uniforms.outBackprop[3]; + let coord = vec4(coordX, coordY, col, rowInner); + ${e(n)} + } + return ${Rt(n)}(0.0); + } + + fn mm_write(batch: i32, row : i32, col : i32, valueInput : ${Rt(n)}) { + if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) { + var value = valueInput; + let outCoord = vec4( + batch, + row / uniforms.outShape[2], + row % uniforms.outShape[2], + col); + result[getIndexFromCoords4D(outCoord, uniforms.outShape)/${n}] = value; + } + }`}class qre{constructor(e){this.variableNames=["x","W"],this.uniforms="filterDims : vec2, pads : vec2, strides : vec2, outBackprop : vec4, dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.outputShape=e.inShape,N(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.isVec4=e.inChannels%4===0&&e.outChannels%4===0,this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workgroupSize=hk(this.dispatchLayout,this.outputShape,this.isVec4),this.elementsPerThread=dk(this.dispatchLayout,this.outputShape,this.isVec4),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread),this.isVec4&&(this.outputComponent=4,this.variableComponents=[4,1]),this.shaderKey=`conv2DDerInputMM_${this.isVec4}_${this.elementsPerThread}`}getUserCode(){const e=this.isVec4?eg(this.elementsPerThread,this.workgroupSize):tg(this.elementsPerThread,this.workgroupSize);return` + ${Hre(this.isVec4?4:1)} + ${e} + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Xre(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,filter:i}=e,{inputShape:o,strides:a,pad:l,dataFormat:c,dimRoundingMode:u}=s,h=wr(c),d=Cn(o,i.shape,a,1,l,u,!1,h),p=[{type:"int32",data:[d.filterHeight,d.filterWidth]},{type:"int32",data:[d.filterHeight-1-d.padInfo.top,d.filterWidth-1-d.padInfo.left]},{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.batchSize,d.outHeight,d.outWidth,d.outChannels]}];let f;if(oe().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE")||d.dataFormat!=="channelsLast")f=new zre(d);else{f=new qre(d);const x=d.inHeight*d.inWidth,m=d.inChannels,g=d.filterHeight*d.filterWidth*d.outChannels;p.push({type:"uint32",data:[x]},{type:"uint32",data:[m]},{type:"uint32",data:[g]})}return t.runWebGPUProgram(f,[r,i],"float32",p)}const Kre={kernelName:hd,backendName:"webgpu",kernelFunc:Xre};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class jre{constructor(e){this.variableNames=["x","W"],this.uniforms="filterDims: vec3, pads: vec3, strides: vec3, dilations: vec3,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="conv3dnaive"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let batch = coords.x; + let d2 = coords.u; + + let xFRCCorner = vec3(coords.y, coords.z, coords.w) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + + let inputDepthNearestVec4 = (uniforms.xShape.u / 4) * 4; + let inputDepthVec4Remainder = uniforms.xShape.u % 4; + + var dotProd = 0.0; + for (var wF = 0; wF < uniforms.filterDims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= uniforms.xShape.y) { + continue; + } + + for (var wR = 0; wR < uniforms.filterDims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= uniforms.xShape.z) { + continue; + } + + for (var wC = 0; wC < uniforms.filterDims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= uniforms.xShape.w) { + continue; + } + + for (var d1 = 0; d1 < inputDepthNearestVec4; d1 += 4) { + let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3) + ); + let wValues = vec4( + getW(wF, wR, wC, d1, d2), + getW(wF, wR, wC, d1 + 1, d2), + getW(wF, wR, wC, d1 + 2, d2), + getW(wF, wR, wC, d1 + 3, d2) + ); + + dotProd += dot(xValues, wValues); + } + + if (inputDepthVec4Remainder == 1) { + dotProd += getX(batch, xF, xR, xC, inputDepthNearestVec4) * + getW(wF, wR, wC, inputDepthNearestVec4, d2); + } else if (inputDepthVec4Remainder == 2) { + let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1) + ); + let wValues = vec2( + getW(wF, wR, wC, inputDepthNearestVec4, d2), + getW(wF, wR, wC, inputDepthNearestVec4 + 1, d2) + ); + dotProd += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2) + ); + let wValues = vec3( + getW(wF, wR, wC, inputDepthNearestVec4, d2), + getW(wF, wR, wC, inputDepthNearestVec4 + 1, d2), + getW(wF, wR, wC, inputDepthNearestVec4 + 2, d2) + ); + dotProd += dot(xValues, wValues); + } + } + } + } + setOutputAtIndex(index, dotProd); + } + }`}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Yre(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:i}=e,{strides:o,pad:a,dilations:l}=s,c=Ri(r.shape,i.shape,o,l,a),u=[c.padInfo.front,c.padInfo.top,c.padInfo.left],h=[{type:"int32",data:[c.filterDepth,c.filterHeight,c.filterWidth]},{type:"int32",data:[...u]},{type:"int32",data:[c.strideDepth,c.strideHeight,c.strideWidth]},{type:"int32",data:[c.dilationDepth,c.dilationHeight,c.dilationWidth]}],d=new jre(c),p=ds(r.dtype,i.dtype);return t.runWebGPUProgram(d,[r,i],p,h)}const Zre={kernelName:dd,backendName:"webgpu",kernelFunc:Yre};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Jre(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,dy:i}=e,{strides:o,pad:a,filterShape:l}=s,c=Ri(r.shape,l,o,1,a),u=new Ure(c),h=[{type:"int32",data:[c.padInfo.front,c.padInfo.top,c.padInfo.left]},{type:"int32",data:[c.strideDepth,c.strideHeight,c.strideWidth]},{type:"int32",data:[c.batchSize]},{type:"int32",data:[c.outDepth]},{type:"int32",data:[c.outHeight]},{type:"int32",data:[c.outWidth]},{type:"int32",data:[c.inDepth]},{type:"int32",data:[c.inHeight]},{type:"int32",data:[c.inWidth]}];return t.runWebGPUProgram(u,[r,i],i.dtype,h)}const Qre={kernelName:A0,backendName:"webgpu",kernelFunc:Jre};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function eie(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,filter:i}=e,{strides:o,pad:a,inputShape:l}=s,c=Ri(l,i.shape,o,1,a),u=new Vre(c),h=[{type:"int32",data:[c.filterDepth,c.filterHeight,c.filterWidth]},{type:"int32",data:[c.filterDepth-1-c.padInfo.front,c.filterHeight-1-c.padInfo.top,c.filterWidth-1-c.padInfo.left]},{type:"int32",data:[c.strideDepth,c.strideHeight,c.strideWidth]},{type:"int32",data:[c.outDepth]},{type:"int32",data:[c.outHeight]},{type:"int32",data:[c.outWidth]},{type:"int32",data:[c.outChannels]}];return t.runWebGPUProgram(u,[r,i],r.dtype,h)}const tie={kernelName:R0,backendName:"webgpu",kernelFunc:eie};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nie=jt({opType:Me.COS}),sie={kernelName:ou,backendName:"webgpu",kernelFunc:nie};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rie=jt({opType:Me.COSH}),iie={kernelName:au,backendName:"webgpu",kernelFunc:rie};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class oie{constructor(e,t,s,r){this.variableNames=["Image","Boxes","BoxInd"],this.uniforms="extrapolationValue : f32,",this.workgroupSize=[64,1,1],this.size=!0;const[i]=t;this.outputShape=[i,s[0],s[1],e],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.methodId=r==="bilinear"?1:0,this.cropHeightBiggerThan1=this.outputShape[1]>1,this.cropWidthBiggerThan1=this.outputShape[2]>1,this.shaderKey=`cropAndResize_${this.methodId}_${this.cropHeightBiggerThan1}_${this.cropWidthBiggerThan1}`}getUserCode(){const[e,t]=["f32(uniforms.imageShape[1] - 1)","f32(uniforms.imageShape[2] - 1)"],[s,r,i]=this.cropHeightBiggerThan1?[`(${e} / f32(uniforms.outShape[1] - 1))`,"(y2-y1) * height_ratio",`y1*${e} + f32(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${e}`],[o,a,l]=this.cropWidthBiggerThan1?[`(${t} / f32(uniforms.outShape[2] - 1))`,"(x2-x1) * width_ratio",`x1*${t} + f32(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${t}`];return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let height_ratio = f32(${s}); + let width_ratio = f32(${o}); + let b = coords[0]; + let y = coords[1]; + let x = coords[2]; + let d = coords[3]; + // get box vals + let y1 = getBoxes(b, 0); + let x1 = getBoxes(b, 1); + let y2 = getBoxes(b, 2); + let x2 = getBoxes(b, 3); + // get image in batch index + let bInd = i32(round(getBoxInd(b))); + if(bInd < 0 || bInd >= uniforms.outShape[0]) { + return; + } + let height_scale = ${r}; + let width_scale = ${a}; + let in_y = ${i}; + if( in_y < 0.0 || in_y > ${e} ) { + setOutputAtIndex(index, uniforms.extrapolationValue); + return; + } + let in_x = ${l}; + if( in_x < 0.0 || in_x > ${t} ) { + setOutputAtIndex(index, uniforms.extrapolationValue); + return; + } + let sourceFracIndexCR = vec2(in_x,in_y); + if(${this.methodId} == 1) { + // Compute the four integer indices. + let sourceFloorCR = vec2(sourceFracIndexCR); + let sourceCeilCR = vec2(ceil(sourceFracIndexCR)); + let topLeft = getImage(bInd, sourceFloorCR.y, sourceFloorCR.x, d); + let bottomLeft = getImage(bInd, sourceCeilCR.y, sourceFloorCR.x, d); + let topRight = getImage(bInd, sourceFloorCR.y, sourceCeilCR.x, d); + let bottomRight = getImage(bInd, sourceCeilCR.y, sourceCeilCR.x, d); + let fracCR = sourceFracIndexCR - vec2(sourceFloorCR); + let top = topLeft + (topRight - topLeft) * fracCR.x; + let bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x; + let newValue = top + (bottom - top) * fracCR.y; + setOutputAtIndex(index, newValue); + } else { + // Compute the coordinators of nearest neighbor point. + let sourceNearestCR = vec2(floor( + sourceFracIndexCR + vec2(0.5,0.5))); + let newValue = getImage( + bInd, sourceNearestCR.y, sourceNearestCR.x, d); + setOutputAtIndex(index, newValue); + } + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const aie=n=>{const{inputs:e,backend:t,attrs:s}=n,{image:r,boxes:i,boxInd:o}=e,{cropSize:a,method:l,extrapolationValue:c}=s,u=new oie(r.shape[3],i.shape,a,l),h=[{type:"float32",data:[c]}];return t.runWebGPUProgram(u,[r,i,o],"float32",h)},lie={kernelName:N0,backendName:"webgpu",kernelFunc:aie};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Zh;(function(n){n.Prod="*",n.Sum="+"})(Zh||(Zh={}));class Dw{constructor(e,t,s,r){this.variableNames=["x"],this.uniforms="index : f32,",this.size=!0,this.workgroupSize=[128,1,1],this.outputShape=t,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.exclusive=s,this.reverse=r,this.op=e,this.shaderKey=`cum_${this.op}_${this.exclusive}_${this.reverse}`}getUserCode(){const e=this.outputShape.length,t=this.op===Zh.Prod?"1.0":"0.0",s=this.exclusive?t:`getX(${Pw(e,"coords",this.op)})`,r=this.outputShape[this.outputShape.length-1];let i="",o="";return this.exclusive?(i=this.reverse?`end != ${r-1}`:"end != 0",o=this.reverse?"end + 1":"end - 1"):(i=this.reverse?`end + pow2 < ${r}`:"end >= pow2",o=this.reverse?"end + pow2":"end - pow2"),` + ${De("index")} { + if (index < uniforms.size) { + var coords = getCoordsFromIndex(index); + + let end = ${Lw(e,"coords",this.op)}; + var val = ${s}; + let pow2 = i32(pow(2.0, uniforms.index)); + if (${i}) { + let idx = ${o}; + ${Lw(e,"coords",this.op)} = idx; + val ${this.op}= getX(${Pw(e,"coords",this.op)}); + } + setOutputAtIndex(index, val); + } + } + `}}function Pw(n,e,t){if(n===1)return`${e}`;if(n===2)return`${e}.x, ${e}.y`;if(n===3)return`${e}.x, ${e}.y, ${e}.z`;if(n===4)return`${e}.x, ${e}.y, ${e}.z, ${e}.w`;throw Error(`Cumulative ${t} for rank ${n} is not yet supported`)}function Lw(n,e,t){if(n===1)return`${e}`;if(n===2)return`${e}.y`;if(n===3)return`${e}.z`;if(n===4)return`${e}.w`;throw Error(`Cumulative ${t} for rank ${n} is not yet supported`)}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Tk(n,e,t,s,r,i){const o=e.shape.length,a=ln([s],o);let l=e;a!=null&&(l=to({inputs:{x:e},backend:t,attrs:{perm:a}}));const c=xn(1,o)[0];if(c!==o-1)throw new Error(`WebGPU cumprod shader expects an inner-most axis=${e.shape.length-1} but got axis=${s}`);const u=l.shape[c];let h=br({inputs:{x:l},backend:t});for(let d=0;d<=Math.ceil(Math.log2(u))-1;d++){const p=new Dw(n,l.shape,!1,i),f=h,x=[{type:"float32",data:[d]}];h=t.runWebGPUProgram(p,[h],h.dtype,x),t.disposeData(f.dataId)}if(r){const d=new Dw(n,l.shape,r,i),p=h,f=[{type:"float32",data:[0]}];h=t.runWebGPUProgram(d,[h],h.dtype,f),t.disposeData(p.dataId)}if(a!=null){const d=no(a),p=to({inputs:{x:h},backend:t,attrs:{perm:d}});return t.disposeData(h.dataId),t.disposeData(l.dataId),p}return h}/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cie(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i,exclusive:o,reverse:a}=s;return Tk(Zh.Prod,r,t,i,o,a)}const uie={kernelName:M0,backendName:"webgpu",kernelFunc:cie};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function hie(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i,exclusive:o,reverse:a}=s;return Tk(Zh.Sum,r,t,i,o,a)}const die={kernelName:pd,backendName:"webgpu",kernelFunc:hie};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pie(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,weights:i}=e,{size:o,binaryOutput:a}=s,l=r.shape.length===1,u=re(i.shape)>0,h=i.dtype,d=l?[r.shape[0]]:[r.shape[0],r.shape[1]],p=l?[o]:[r.shape[0],o],f=sr({backend:t,attrs:{shape:p,value:0,dtype:h}}),x=new wk(d,u,a),m=[{type:"int32",data:[o]}],g=u?[r,i]:[r];return t.runWebGPUProgram(x,g,h,m,f)}const fie={kernelName:$0,backendName:"webgpu",kernelFunc:pie};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class mie{constructor(e,t){this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.uniforms="blockSize : i32,",this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey=`depthToSpace_${t}`,this.dataFormat=t}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let b = coords[0]; + let h = ${this.getHeightCoordString()}; + let w = ${this.getWidthCoordString()}; + let d = ${this.getDepthCoordString()}; + + let in_h = h / uniforms.blockSize; + let offset_h = h % uniforms.blockSize; + let in_w = w / uniforms.blockSize; + let offset_w = w % uniforms.blockSize; + let offset_d = (offset_h * uniforms.blockSize + offset_w) * + ${this.getOutputDepthSize()}; + let in_d = d + offset_d; + + let rlt = ${this.getInputSamplingString()}; + setOutputAtIndex(index, rlt); + } + }`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?"uniforms.outShape[3]":"uniforms.outShape[1]"}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gie(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{blockSize:i,dataFormat:o}=s,a=r.shape[0],l=o==="NHWC"?r.shape[1]:r.shape[2],c=o==="NHWC"?r.shape[2]:r.shape[3],u=o==="NHWC"?r.shape[3]:r.shape[1],h=l*i,d=c*i,p=u/(i*i),f=o==="NHWC"?[a,h,d,p]:[a,p,h,d],x=[{type:"int32",data:[i]}],m=new mie(f,o);return t.runWebGPUProgram(m,[r],r.dtype,x)}const xie={kernelName:D0,backendName:"webgpu",kernelFunc:gie};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class vie{constructor(e,t,s,r=!1,i=null,o=!1){this.variableNames=["x","W"],this.uniforms="pads : vec2, inDims : vec2,",this.workgroupSize=[16,16,1],this.outputShape=e,this.dispatchLayout={x:[3],y:[2],z:[0,1]},this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),r&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),this.addBias=r,this.activation=i,this.hasPreluActivation=o,this.filterHeight=t,this.filterWidth=s,this.shaderKey=`depthwiseNCHW_${this.activation}_${this.filterHeight}_${this.filterWidth}`}getUserCode(){const e=this.filterWidth*this.filterHeight,t=this.workgroupSize[0]*this.workgroupSize[1]*this.workgroupSize[2],s=this.workgroupSize[1]+this.filterHeight-1,r=this.workgroupSize[0]+this.filterWidth-1;return` + ${Do(this.activation,this.hasPreluActivation,!1,4)} + + var mm_Asub : array, ${s}>; + var mm_Bsub : array, ${this.filterHeight}>; + fn readX(batch : i32, channel : i32, row : i32, col : i32) -> f32 { + var value = 0.0; + if (row >=0 && row < uniforms.inDims[0] && col >=0 && col < uniforms.inDims[1]) + { + value = getX(batch, channel, row, col); + } + return value; + } + + ${De()} { + let coords = getOutputCoords(); + let batch = coords[0]; + let xRCCorner = vec2(coords.zw) - uniforms.pads; + let channelMul = uniforms.wShape[3]; + let d1 = coords[1] / channelMul; + let q = coords[1] % channelMul; + + let inputRowStart = xRCCorner.x; + let inputColStart = xRCCorner.y; + + let localRow = i32(localId.y); + let localCol = i32(localId.x); + + // Load one tile of X into local memory. + for (var inputRow = localRow; inputRow < ${s}; inputRow = inputRow + ${this.workgroupSize[1]}) { + for (var inputCol = localCol; inputCol < ${r}; inputCol = inputCol + ${this.workgroupSize[0]}) { + let rowOffset = inputRow - localRow; + let colOffset = inputCol - localCol; + mm_Asub[inputRow][inputCol] = readX(batch, d1, inputRowStart + rowOffset, inputColStart + colOffset); + } + } + + // Load one tile of W into local memory. + var wIndex = i32(localIndex); + ${e, inDims : vec2, virtualWidth : i32,",this.workgroupSize=[64,1,1],this.workPerThread=4,this.outputComponent=4,this.outputShape=e.outShape,this.virtualWidth=Math.ceil(this.outputShape[2]/this.workPerThread)*this.workPerThread;const i=[this.outputShape[0],this.outputShape[1],this.virtualWidth,this.outputShape[3]];this.dispatchLayout=Xe(i),this.dispatch=Le(this.dispatchLayout,i,this.workgroupSize,[this.outputComponent*this.workPerThread,1,1]),N(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=s,this.hasPreluActivation=r,this.shaderKey=`depthwiseVec4_${s}_${this.convInfo.filterHeight}_${this.convInfo.filterWidth}_${this.convInfo.strideHeight}_${this.convInfo.strideWidth}_${this.workPerThread}`}getUserCode(){const e=(this.workPerThread-1)*this.convInfo.strideWidth+this.convInfo.filterWidth,t=this.convInfo.strideHeight,s=this.convInfo.strideWidth;return` + ${Do(this.activation,this.hasPreluActivation,!0,4)} + fn readX(batch : i32, row : i32, col : i32, channel : i32) -> vec4 { + var value = vec4(0.0); + if (col >=0 && col < uniforms.inDims[1]) { + value = getX(batch, row, col, channel); + } + return value; + } + + ${De("index")} { + let width0 = uniforms.outShape[3] / ${this.outputComponent}; + let d1 = (index % width0) * ${this.outputComponent}; + var index1 = index / width0; + let width1 = uniforms.virtualWidth / ${this.workPerThread}; + let c = (index1 % width1) * ${this.workPerThread}; + index1 = index1 / width1; + let r = index1 % uniforms.outShape[1]; + let batch = index1 / uniforms.outShape[1]; + + let xRCCorner = vec2(r, c) * vec2(${t}, ${s}) - uniforms.pads; + + let xRCorner = xRCCorner.x; + let xCCorner = xRCCorner.y; + var xVals : array, ${e}>; + var dotProd : array, ${this.workPerThread}>; + for (var i = 0; i < ${this.workPerThread}; i++) { + dotProd[i] = vec4(0.0); + } + + // Use constant instead of uniform can give better performance. + for (var wR = 0; wR < ${this.convInfo.filterHeight}; wR = wR + 1) { + let xR = xRCorner + wR; + if (xR >=0 && xR < uniforms.inDims[0]) { + for (var i = 0; i < ${e}; i++) { + xVals[i] = readX(batch, xR, xCCorner + i, d1); + } + for (var wC = 0; wC < ${this.convInfo.filterWidth}; wC = wC + 1) { + let wValue = getW(wR, wC, d1, 0); + for (var i = 0; i < ${this.workPerThread}; i++) { + dotProd[i] = fma(xVals[i * ${s} + wC], wValue, dotProd[i]); + } + } + } + } + + for (var i = 0; i < ${this.workPerThread}; i = i + 1) { + let coords = vec4(batch, r, c + i, d1); + if (coordsInBounds4D(coords, uniforms.outShape)) { + var value = dotProd[i]; + ${Wl(this.addBias,this.activation)} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + } + } + `}}/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ek{constructor(e,t=!1,s=null,r=!1){this.variableNames=["x","W"],this.uniforms=`pads : vec2, inDims : vec2, filterHeight : i32, + filterWidth : i32, strides : vec2, dilations : vec2,`,this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.isChannelsLast=e.dataFormat==="channelsLast",t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=s,this.hasPreluActivation=r,this.shaderKey=`depthwise_${this.activation}_${this.isChannelsLast}`}getUserCode(){const e=this.isChannelsLast?"getX(batch, xR, xC, d1);":"getX(batch, d1, xR, xC);";return` + ${Do(this.activation,this.hasPreluActivation,!1,4)} + + ${De("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let batch = coords[0]; + let xRCCorner = vec2(coords.${this.isChannelsLast?"yz":"zw"}) * uniforms.strides - uniforms.pads; + let d2 = coords[${this.isChannelsLast?3:1}]; + let channelMul = uniforms.wShape[3]; + let d1 = d2 / channelMul; + let q = d2 % channelMul; + + let inputRowStart = xRCCorner.x; + let inputColStart = xRCCorner.y; + let inputRowEnd = inputRowStart + uniforms.filterHeight * + uniforms.dilations[0]; + let inputColEnd = inputColStart + uniforms.filterWidth * + uniforms.dilations[1]; + + // Convolve x(?, ?, d1)|x(d1, ?, ?) with w(:, :, d1, q) to get + // y(yR, yC, d2)|y(d2, yR, yC). ? = to be determined. : = across all + // values in that axis. x(?, ?, d1) and y(yR, yC, d2) is for NHWC. + // x(d1, ?, ?) and y(d2, yR, yC) is for NCHW. + var value = 0.0; + + // Extract if checking out of for loop for performance. + if (inputRowStart >= 0 && inputColStart >= 0 && + inputRowEnd < uniforms.inDims[0] && + inputColEnd < uniforms.inDims[1]) { + for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) { + let xR = inputRowStart + wR * uniforms.dilations[0]; + + for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) { + let xC = inputColStart + wC * uniforms.dilations[1]; + + let xVal = ${e}; + let wVal = getW(wR, wC, d1, q); + value = value + xVal * wVal; + } + } + } else { + for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) { + let xR = inputRowStart + wR * uniforms.dilations[0]; + + if (xR < 0 || xR >= uniforms.inDims[0]) { + continue; + } + + for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) { + let xC = inputColStart + wC * uniforms.dilations[1]; + + if (xC < 0 || xC >= uniforms.inDims[1]) { + continue; + } + + let xVal = ${e}; + let wVal = getW(wR, wC, d1, q); + value = value + xVal * wVal; + } + } + } + ${Wl(this.addBias,this.activation)} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bie(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:i}=e,{strides:o,pad:a,dataFormat:l,dilations:c,dimRoundingMode:u}=s,h=wr(l);let d=c;d==null&&(d=[1,1]);const p=Cn(r.shape,i.shape,o,d,a,u,!0,h),f=[{type:"int32",data:[p.padInfo.top,p.padInfo.left]},{type:"int32",data:[p.inHeight,p.inWidth]}],x=p.dataFormat==="channelsLast";let m;return!x&&p.inHeight>16&&p.inWidth>16&&p.strideHeight===1&&p.strideWidth===1&&p.dilationWidth===1&&p.dilationHeight===1&&p.inChannels===p.outChannels?m=new vie(p.outShape,p.filterHeight,p.filterWidth):x&&p.outHeight>4&&p.outWidth>4&&p.strideWidth<=2&&p.inChannels===p.outChannels&&p.dilationHeight===1&&p.dilationWidth===1&&p.inChannels%4===0?(m=new Ik(p),f.push({type:"int32",data:[m.virtualWidth]})):(m=new Ek(p),f.push({type:"int32",data:[p.filterHeight]},{type:"int32",data:[p.filterWidth]},{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.dilationHeight,p.dilationWidth]})),t.runWebGPUProgram(m,[r,i],r.dtype,f)}const yie={kernelName:fd,backendName:"webgpu",kernelFunc:bie};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class wie{constructor(e){this.variableNames=["x","dy"],this.uniforms=`strides : vec2, pads : vec2, filterDims : vec2, outHeight : i32, + outWidth : i32, inHeight : i32, inWidth : i32, batchSize : i32, channelMul : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.filterShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="depthwise_conv2d_backprop_filter"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let wR = coords[0]; + let wC = coords[1]; + let d1 = coords[2]; + let dm = coords[3]; + let d2 = d1 * uniforms.channelMul + dm; + + var dotProd = 0.0; + for (var b = 0; b < uniforms.batchSize; b++) { + for (var yR = 0; yR < uniforms.outHeight; yR++) { + let xR = wR + yR * uniforms.strides[0] - uniforms.pads[0]; + + if (xR < 0 || xR >= uniforms.inHeight) { + continue; + } + + for (var yC = 0; yC < uniforms.outWidth; yC++) { + let xC = wC + yC * uniforms.strides[1] - uniforms.pads[1]; + + if (xC < 0 || xC >= uniforms.inWidth) { + continue; + } + + let dyValue = getDy(b, yR, yC, d2); + let xValue = getX(b, xR, xC, d1); + dotProd += xValue * dyValue; + } + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}class Sie{constructor(e){this.variableNames=["dy","W"],this.uniforms=`strides : vec2, pads : vec2, filterDims : vec2, + outHeight : i32, outWidth : i32, channelMul : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="depthwise_conv2d_backprop_input"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords[0]; + let d1 = coords[3]; + let dyCorner = coords.yz - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + + var dotProd = 0.0; + for (var wR = 0; wR < uniforms.filterDims[0]; wR++) { + let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]); + + if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) { + continue; + } + + let idyR = i32(dyR); + let wRPerm = uniforms.filterDims[0] - 1 - wR; + + for (var wC = 0; wC < uniforms.filterDims[1]; wC++) { + let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]); + + if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) { + continue; + } + + let idyC = i32(dyC); + let wCPerm = uniforms.filterDims[1] - 1 - wC; + + for (var dm = 0; dm < uniforms.channelMul; dm++) { + let d2 = d1 * uniforms.channelMul + dm; + let xValue = getDy(batch, idyR, idyC, d2); + let wValue = getW(wRPerm, wCPerm, d1, dm); + dotProd += xValue * wValue; + } + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Cie(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,dy:i}=e,{strides:o,dilations:a,pad:l,dimRoundingMode:c,filterShape:u}=s,h=Cn(r.shape,u,o,a,l,c,!0),d=new wie(h),p=[{type:"int32",data:[h.strideHeight,h.strideWidth]},{type:"int32",data:[h.padInfo.top,h.padInfo.left]},{type:"int32",data:[h.filterHeight,h.filterWidth]},{type:"int32",data:[h.outHeight]},{type:"int32",data:[h.outWidth]},{type:"int32",data:[h.inHeight]},{type:"int32",data:[h.inWidth]},{type:"int32",data:[h.batchSize]},{type:"int32",data:[h.outChannels/h.inChannels]}];return t.runWebGPUProgram(d,[r,i],"float32",p)}const _ie={kernelName:P0,backendName:"webgpu",kernelFunc:Cie};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Tie(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,filter:i}=e,{strides:o,dilations:a,pad:l,dimRoundingMode:c,inputShape:u}=s,h=Cn(u,i.shape,o,a,l,c,!0),d=new Sie(h),p=[{type:"int32",data:[h.strideHeight,h.strideWidth]},{type:"int32",data:[h.filterHeight-1-h.padInfo.top,h.filterWidth-1-h.padInfo.left]},{type:"int32",data:[h.filterHeight,h.filterWidth]},{type:"int32",data:[h.outHeight]},{type:"int32",data:[h.outWidth]},{type:"int32",data:[h.outChannels/h.inChannels]}];return t.runWebGPUProgram(d,[r,i],r.dtype,p)}const Iie={kernelName:L0,backendName:"webgpu",kernelFunc:Tie};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Eie{constructor(e){this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e,e],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="diag"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let value = select(0.0, getX(coords[0]), coords[0] == coords[1]); + setOutputAtIndex(index, value); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function kie(n){const{inputs:e,backend:t}=n,{x:s}=e,r=[...s.shape,...s.shape],i=re(s.shape),o=tt({inputs:{x:s},backend:t,attrs:{shape:[i]}}),a=new Eie(i),l=t.runWebGPUProgram(a,[o],o.dtype),c=tt({inputs:{x:l},backend:t,attrs:{shape:r}});return t.disposeData(o.dataId),t.disposeData(l.dataId),c}const Aie={kernelName:h2,backendName:"webgpu",kernelFunc:kie};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Rie{constructor(e){this.variableNames=["x","w"],this.uniforms="filterDims: vec2, pads: vec2, strides: vec2, dilations: vec2",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="dilation2d"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let neg_infinity = -3.4e38; + let coords = getOutputCoords(); + let batch = coords.x; + let d1 = coords.w; + let outTopLeftCorner = coords.yz * uniforms.strides - uniforms.pads; + let hBeg = outTopLeftCorner.x; + let wBeg = outTopLeftCorner.y; + + var curVal = neg_infinity; + for (var h = 0; h < uniforms.filterDims[0]; h = h + 1) { + let hIn = hBeg + h * uniforms.dilations[0]; + + if (hIn >= 0 && hIn < uniforms.xShape[1]) { + for (var w = 0; w < uniforms.filterDims[1]; w = w + 1) { + let wIn = wBeg + w * uniforms.dilations[1]; + + if (wIn >= 0 && wIn < uniforms.xShape[2]) { + let val = getX(batch, hIn, wIn, d1) + getW(h, w, d1); + if (val > curVal) { + curVal = val; + } + } + } + } + } + + setOutputAtIndex(index, curVal); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Mie(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:i}=e,{strides:o,pad:a,dilations:l}=s,c=Sa(r.shape,i.shape,o,a,"NHWC",l),u=[c.padInfo.top,c.padInfo.left],h=[{type:"int32",data:[c.filterHeight,c.filterWidth]},{type:"int32",data:[...u]},{type:"int32",data:[c.strideHeight,c.strideWidth]},{type:"int32",data:[c.dilationHeight,c.dilationWidth]}],d=new Rie(c);return t.runWebGPUProgram(d,[r,i],r.dtype,h)}const Nie={kernelName:md,backendName:"webgpu",kernelFunc:Mie};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class $ie{constructor(e,t){if(this.variableNames=["x","w","dy"],this.uniforms="filterDims: vec2, pads: vec2, strides: vec2, dilations: vec2, dySize: i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=e.inShape,this.dispatchLayout=Xe(e.outShape),this.dispatch=Le(this.dispatchLayout,e.outShape,this.workgroupSize),t!=="float32"&&t!=="int32")throw new Error(`Dilation2DBackpropInput only supports float32 and int32 + types, does not support ${t} type.`);this.type=t,this.shaderKey="dilation2DBackpropInput"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.dySize) { + let coords = getDyCoordsFromIndex(index); + let b = coords[0]; + let r = coords[1]; + let c = coords[2]; + let d = coords[3]; + + let dyCorner = vec2(r, c) * uniforms.strides - uniforms.pads; + var curVal = -3.4e38; // neg_infinity + var xRMax = 0; + var xCMax = 0; + + // In the case of multiple argmax branches, we only back-propagate + // along the last branch, i.e., the one with largest value of + // 'wR * uniforms.filterDims[1] + wC', similarly to the max-pooling + // backward routines. + for (var wR = 0; wR < uniforms.filterDims[0]; wR++) { + let xR = dyCorner.x + wR * uniforms.dilations[0]; + + if (xR >= 0 && xR < uniforms.xShape[1]) { + for (var wC = 0; wC < uniforms.filterDims[1]; wC++) { + let xC = dyCorner.y + wC * uniforms.dilations[1]; + + if (xC >= 0 && xC < uniforms.xShape[2]) { + let val = getX(b, xR, xC, d) + getW(wR, wC, d); + if (val > curVal) { + curVal = val; + xRMax = xR; + xCMax = xC; + } + } + } + } + } + + let flatIndexIn = d + uniforms.xShape[3] * + (xCMax + uniforms.xShape[2] * (xRMax + uniforms.xShape[1] * b)); + let value = getDy(b, r, c, d); + ${Aa("&result[flatIndexIn]","value",this.type)} + } + } + `}}class Die{constructor(e,t,s){if(this.variableNames=["x","w","dy"],this.uniforms="filterDims: vec2, pads: vec2, strides: vec2, dilations: vec2, dySize: i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=e.filterShape,this.dispatchLayout=Xe(e.outShape),this.dispatch=Le(this.dispatchLayout,e.outShape,this.workgroupSize),s!=="float32"&&s!=="int32")throw new Error(`Dilation2DBackpropFilter only supports float32 and int32 + types, does not support ${s} type.`);this.type=s,this.shaderKey="dilation2DBackpropFilter"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.dySize) { + let coords = getDyCoordsFromIndex(index); + let b = coords[0]; + let r = coords[1]; + let c = coords[2]; + let d = coords[3]; + + let dyCorner = vec2(r, c) * uniforms.strides - uniforms.pads; + var curVal = -3.4e38; // neg_infinity + var wRMax = 0; + var wCMax = 0; + + // In the case of multiple argmax branches, we only back-propagate + // along the last branch, i.e., the one with largest value of + // 'wR * uniforms.filterDims[1] + wC', similarly to the max-pooling + // backward routines. + for (var wR = 0; wR < uniforms.filterDims[0]; wR++) { + let xR = dyCorner.x + wR * uniforms.dilations[0]; + + if (xR >= 0 && xR < uniforms.xShape[1]) { + for (var wC = 0; wC < uniforms.filterDims[1]; wC++) { + let xC = dyCorner.y + wC * uniforms.dilations[1]; + + if (xC >= 0 && xC < uniforms.xShape[2]) { + let val = getX(b, xR, xC, d) + getW(wR, wC, d); + if (val > curVal) { + curVal = val; + wRMax = wR; + wCMax = wC; + } + } + } + } + } + + let flatIndexIn = d + uniforms.wShape[2] * (wCMax + wRMax * uniforms.wShape[1]); + let value = getDy(b, r, c, d); + ${Aa("&result[flatIndexIn]","value",this.type)} + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Pie(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:i,dy:o}=e,{strides:a,pad:l,dilations:c}=s,u=Sa(r.shape,i.shape,a,l,"NHWC",c),h=i.dtype,d=new Die(u,i.shape,h),p=[{type:"int32",data:[u.filterHeight,u.filterWidth]},{type:"int32",data:[u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[re(u.outShape)]}],f=sr({backend:t,attrs:{shape:i.shape,value:0,dtype:h}});return t.runWebGPUProgram(d,[r,i,o],h,p,f)}const Lie={kernelName:Mf,backendName:"webgpu",kernelFunc:Pie};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Fie(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:i,dy:o}=e,{strides:a,pad:l,dilations:c}=s,u=Sa(r.shape,i.shape,a,l,"NHWC",c),h=r.dtype,d=new $ie(u,h),p=[{type:"int32",data:[u.filterHeight,u.filterWidth]},{type:"int32",data:[u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[re(u.outShape)]}],f=sr({backend:t,attrs:{shape:u.inShape,value:0,dtype:h}});return t.runWebGPUProgram(d,[r,i,o],h,p,f)}const Oie={kernelName:Rf,backendName:"webgpu",kernelFunc:Fie};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class zie{constructor(e,t,s){this.variableNames=["Image"],this.uniforms="alpha: f32,",this.workgroupSize=[64,1,1],this.pixelsOpType=Bc.DRAW,this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.type=t,this.textureFormat=s,this.shaderKey=`draw_${t}_${s}`}getUserCode(){let e;const t=this.type==="float32"?"value":"value / 255.0";return e=` + if (uniforms.numChannels == 1) { + rgba[0] = ${t}; + rgba[1] = ${t}; + rgba[2] = ${t}; + } else { + rgba[d] = ${t}; + }`,` + @group(0) @binding(0) var outImage : texture_storage_2d<${this.textureFormat}, write>; + ${De("index")} { + if (index < uniforms.size) { + var rgba = vec4(0.0, 0.0, 0.0, uniforms.alpha); + for (var d = 0; d < uniforms.numChannels; d = d + 1) { + let value = f32(inBuf[index * uniforms.numChannels + d]); + ${e} + } + rgba.x = rgba.x * rgba.w; + rgba.y = rgba.y * rgba.w; + rgba.z = rgba.z * rgba.w; + let coords = getCoordsFromIndex(index); + textureStore(outImage, vec2(coords.yx), rgba); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use backend file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Bie(n){const{inputs:e,backend:t,attrs:s}=n,{image:r}=e,{canvas:i,options:o}=s,[a,l]=r.shape.slice(0,2),{imageOptions:c}=o||{},u=c?.alpha||1,h=t.device.features.has("bgra8unorm-storage")?"bgra8unorm":"rgba8unorm",d=[a,l],p=new zie(d,r.dtype,h);i.width=l,i.height=a;const f="webgpu";let x=i.getContext(f),m;x||(m=new OffscreenCanvas(l,a),x=m.getContext(f));const g=r.shape.length===3?r.shape[2]:1;x.configure({device:t.device,format:h,usage:GPUTextureUsage.STORAGE_BINDING,alphaMode:"premultiplied"});const v="int32",b=t.makeTensorInfo(d,v),y=t.tensorMap.get(b.dataId);y.resource=x.getCurrentTexture(),y.external=!0;const w=[{type:"uint32",data:[g]},{type:"float32",data:[u]}];if(t.runWebGPUProgram(p,[r],v,w,b),m){const C=i.getContext("2d");if(!C)throw new Error("Please make sure this canvas has only been used for 2d or webgpu context!");C.drawImage(m,0,0)}return t.disposeData(b.dataId),r}const Uie={kernelName:JS,backendName:"webgpu",kernelFunc:Bie};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kk=xs({opType:bt.MUL,cpuKernelImpl:qne,supportsComplex:!0}),Vie={kernelName:Tu,backendName:"webgpu",kernelFunc:kk};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ak(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i,keepDims:o}=s;return Hl(r,i,o,"sum",t)}const Wie={kernelName:Kd,backendName:"webgpu",kernelFunc:Ak};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Gie(n){const{inputs:e,backend:t,attrs:s}=n,{equation:r}=s,i=e,{allDims:o,summedDims:a,idDims:l}=Rm(r,i.length);Nm(o.length,l,i);const{path:c,steps:u}=$m(a,l),h=u.length;let d=null,p=o.length;const f=[];for(let x=0;x=0&&(d=Ak({inputs:{x:d},backend:t,attrs:{axis:c[x]-(o.length-p),keepDims:!1}}),f.push(d)),p--)}for(const x of f)x!==d&&t.disposeData(x.dataId);return d}const Hie={kernelName:F0,backendName:"webgpu",kernelFunc:Gie};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qie=jt({opType:Me.ELU}),Xie={kernelName:cu,backendName:"webgpu",kernelFunc:qie};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Kie=n=>{const{inputs:e,backend:t}=n,{dy:s,y:r}=e,i=new r0(bt.ELU_DER,s.shape,r.shape);return t.runWebGPUProgram(i,[s,r],s.dtype)},jie={kernelName:O0,backendName:"webgpu",kernelFunc:Kie};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Yie=xs({opType:bt.EQUAL,dtype:"bool",cpuKernelImpl:Mne}),Zie={kernelName:gd,backendName:"webgpu",kernelFunc:Yie};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Jie=jt({opType:Me.ERF}),Qie={kernelName:uu,backendName:"webgpu",kernelFunc:Jie};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eoe=jt({opType:Me.EXP,cpuKernelImpl:Nne,dtype:"float32"}),toe={kernelName:hu,backendName:"webgpu",kernelFunc:eoe};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ax(n){const{inputs:e,attrs:t,backend:s}=n,{dim:r}=t,{input:i}=e,o=i.shape.length,a=i.shape.slice();let l=r;return r<0&&(N(-(o+1)<=r,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+r+1),a.splice(l,0,1),tt({inputs:{x:i},backend:s,attrs:{shape:a}})}const noe={kernelName:xd,backendName:"webgpu",kernelFunc:Ax};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const soe=jt({opType:Me.EXPM1,cpuKernelImpl:$ne}),roe={kernelName:du,backendName:"webgpu",kernelFunc:soe};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Fw{constructor(e,t){this.variableNames=["real","imag"],this.outputShape=[],this.uniforms="exponentMultiplier : f32, denominator: f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.component=e,this.shaderKey=`fft_${e}`}getUserCode(){return` + fn unaryOpComplex(real: f32, expR: f32, imag: f32, expI: f32) -> f32 { + ${this.component==="real"?"return real * expR - imag * expI;":"return real * expI + imag * expR;"} + } + + fn mulMatDFT(batch: i32, index: i32) -> f32 { + let indexRatio = f32(index) / f32(uniforms.realShape[1]); + let exponentMultiplierTimesIndexRatio = + uniforms.exponentMultiplier * indexRatio; + + var result = 0.0; + + for (var i = 0; i < uniforms.realShape[1]; i = i + 1) { + // x = (-2|2 * PI / N) * index * i; + let x = exponentMultiplierTimesIndexRatio * f32(i); + let expR = cos(x); + let expI = sin(x); + let real = getReal(batch, i); + let imag = getImag(batch, i); + + result = result + + unaryOpComplex(real, expR, imag, expI) / uniforms.denominator; + } + + return result; + } + + ${De("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + setOutputAtIndex(index, mulMatDFT(coords[0], coords[1])); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Rk(n,e,t){const s=t.tensorMap.get(n.dataId),r=re(n.shape),i=n.shape[n.shape.length-1],o=r/i,a=[],l=tt({inputs:{x:n},backend:t,attrs:{shape:[o,i]}});a.push(l);const c=l.shape,u=new Fw("real",c),h=new Fw("imag",c),d=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:c},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:c}],p=e?2*Math.PI:-2*Math.PI,f=e?c[1]:1,x=[{type:"float32",data:[p]},{type:"float32",data:[f]}],m=t.runWebGPUProgram(u,d,"float32",x);a.push(m);const g=t.runWebGPUProgram(h,d,"float32",x);a.push(g);const v=Gl({inputs:{real:m,imag:g},backend:t});a.push(v);const b=tt({inputs:{x:v},backend:t,attrs:{shape:n.shape}});return a.forEach(y=>t.disposeData(y.dataId)),b}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ioe(n){const{inputs:e,backend:t}=n,{input:s}=e;return Rk(s,!1,t)}const ooe={kernelName:z0,backendName:"webgpu",kernelFunc:ioe};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class aoe{constructor(e){this.outputShape=[],this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="flipLeftRight"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let coordX = uniforms.xShape[2] - coords[2] - 1; + let outputValue = getX(coords[0], coords[1], coordX, coords[3]); + setOutputAtIndex(index, outputValue); + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const loe={kernelName:U0,backendName:"webgpu",kernelFunc:({inputs:n,backend:e})=>{const{image:t}=n,s=e,r=new aoe(t.shape);return s.runWebGPUProgram(r,[t],t.dtype)}};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const coe=jt({opType:Me.FLOOR,cpuKernelImpl:Dne}),uoe={kernelName:pu,backendName:"webgpu",kernelFunc:coe};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hoe=xs({opType:bt.FLOOR_DIV,cpuKernelImpl:Pne,dtype:"int32"}),doe={kernelName:fu,backendName:"webgpu",kernelFunc:hoe};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class poe{constructor(e,t,s=!1){this.pixelsOpType=Bc.FROM_PIXELS,this.outputShape=[0],this.variableNames=[],this.workgroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize,[t,1,1]),this.importVideo=s,this.shaderKey=`fromPixels_${this.importVideo}`}getUserCode(){const e=this.importVideo?"textureLoad(src, vec2(coords.yx));":"textureLoad(src, vec2(coords.yx), 0)";return` + @binding(1) @group(0) var src: ${this.importVideo?"texture_external":"texture_2d"}; + ${De("index")} { + let flatIndex = index * uniforms.numChannels; + if (flatIndex < uniforms.size) { + let coords = getCoordsFromIndex(flatIndex); + let values = ${e}; + for (var i = 0; i < uniforms.numChannels; i = i + 1) { + result[flatIndex + i] = i32(floor(255.0 * values[i])); + } + } + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use backend file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const foe={kernelName:oC,backendName:"webgpu",kernelFunc:moe};let jl,Gg=oe().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function moe(n){const{inputs:e,backend:t,attrs:s}=n;let{pixels:r}=e;const{numChannels:i}=s;if(r==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");const o=typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement,a=typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement,l=typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas,c=typeof ImageBitmap<"u"&&r instanceof ImageBitmap,[u,h]=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],d=[h,u,i],p=oe().getBool("WEBGPU_IMPORT_EXTERNAL_TEXTURE")&&o,f=o||a;if(c||l||f){let v;if(p)v=t.device.importExternalTexture({source:r});else{if(f){const B=oe().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(jl==null||B!==Gg)&&(Gg=B,jl=document.createElement("canvas").getContext("2d",{willReadFrequently:Gg})),jl.canvas.width=u,jl.canvas.height=h,jl.drawImage(r,0,0,u,h),r=jl.canvas}const _=GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,F=t.textureManager.acquireTexture(d[1],d[0],"rgba8unorm",_);t.queue.copyExternalImageToTexture({source:r},{texture:F},[d[1],d[0]]),v=F}const b=re(d),y=it(d),w=new poe(d,i,p),C=[{type:"uint32",data:[b]},{type:"uint32",data:[i]},{type:"uint32",data:[...y]}],T=t.makeTensorInfo([h,u],"int32"),E=t.tensorMap.get(T.dataId);E.resource=v;const R=t.runWebGPUProgram(w,[T],"int32",C);return t.disposeData(T.dataId),R}const x=r.data;let m=x;if(i!=null&&i!==4){m=new Uint8Array(r.width*r.height*i);const v=x.length;let b=0;for(let y=0;y(xValue, -meanValue, offsetValue), vec3(inv, inv, 1.0))); + } + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xoe={kernelName:vd,backendName:"webgpu",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{x:s,scale:r,offset:i,mean:o,variance:a}=n,{varianceEpsilon:l}=e,c=t,u=[s,o,a];let h=null;i!=null&&(h=i.shape,u.push(i));let d=null;r!=null&&(d=r.shape,u.push(r));const p=new goe(s.shape,o.shape,a.shape,h,d),f=[{type:"float32",data:[l]}];return c.runWebGPUProgram(p,u,s.dtype,f)}};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function voe(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:i,bias:o,preluActivationWeights:a}=e,{strides:l,pad:c,dataFormat:u,dilations:h,dimRoundingMode:d,activation:p,leakyreluAlpha:f}=s,x=wr(u),m=Cn(r.shape,i.shape,l,h,c,d,!1,x);return _k({x:r,filter:i,convInfo:m,backend:t,bias:o,preluActivationWeights:a,leakyreluAlpha:f,activation:p})}const boe={kernelName:Lh,backendName:"webgpu",kernelFunc:voe};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yoe(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,filter:i,bias:o,preluActivationWeights:a}=e,{strides:l,pad:c,dilations:u,dimRoundingMode:h,activation:d,leakyreluAlpha:p}=s;let f=u;f==null&&(f=[1,1]),N(gs(l,f),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${f}'`);const x=Cn(r.shape,i.shape,l,f,c,h,!0),m=[r,i],g=o!=null,v=a!=null;g&&m.push(o),v&&m.push(a);const b=[{type:"int32",data:[x.padInfo.top,x.padInfo.left]},{type:"int32",data:[x.inHeight,x.inWidth]}];let y;return x.outHeight>4&&x.outWidth>4&&x.strideWidth<=2&&x.inChannels===x.outChannels&&x.dilationHeight===1&&x.dilationWidth===1&&x.inChannels%4===0?(y=new Ik(x,g,d,v),b.push({type:"int32",data:[y.virtualWidth]})):(y=new Ek(x,g,d,v),b.push({type:"int32",data:[x.filterHeight]},{type:"int32",data:[x.filterWidth]},{type:"int32",data:[x.strideHeight,x.strideWidth]},{type:"int32",data:[x.dilationHeight,x.dilationWidth]})),d==="leakyrelu"&&(b.push({type:"float32",data:[p]}),y.uniforms+=" alpha : f32,"),t.runWebGPUProgram(y,m,"float32",b)}const woe={kernelName:I2,backendName:"webgpu",kernelFunc:yoe};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Soe{constructor(e,t){this.variableNames=["A","indices"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey=`gathernd_${e}`,this.sliceDim=e,this.uniforms=`sliceDim : i32, strides : ${zn(e)},`}getUserCode(){let e;return this.sliceDim>1?e="uniforms.strides[j]":e="uniforms.strides",` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + var flattenIndex = 0; + for (var j = 0; j < uniforms.sliceDim; j = j + 1) { + let indexTemp = i32(round(getIndices(coords[0], j))); + let strideNum = ${e}; + flattenIndex = flattenIndex + indexTemp * strideNum; + } + + setOutputAtIndex(index, getA(flattenIndex, coords[1])); + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Coe(n){const{inputs:e,backend:t}=n,{params:s,indices:r}=e,i=r.shape,o=i[i.length-1],a=re(s.shape),[l,c,u,h]=xm(s,r),d=tt({inputs:{x:r},backend:t,attrs:{shape:[c,o]}}),p=tt({inputs:{x:s},backend:t,attrs:{shape:[re(s.shape)/u,u]}});if(t.shouldExecuteOnCPU([s,r])||s.dtype==="string"){const v=t.readSync(r.dataId),b=t.bufferSync(s),y=Lne(v,b,s.dtype,c,o,u,h,s.shape,a);return t.makeTensorInfo(l,s.dtype,y.values)}const f=new Soe(o,[c,u]),x=[{type:"int32",data:[o]},{type:"int32",data:h}],m=t.runWebGPUProgram(f,[p,d],p.dtype,x),g=tt({inputs:{x:m},backend:t,attrs:{shape:l}});return t.disposeData(d.dataId),t.disposeData(p.dataId),t.disposeData(m.dataId),g}const _oe={kernelName:d2,backendName:"webgpu",kernelFunc:Coe};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Toe{constructor(e,t){this.variableNames=["A","indices"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.slice(),this.aShape=e,this.outputShape=t,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="gather"}getUserCode(){const e=Ioe(this.aShape);return` + ${De("index")} { + if (index < uniforms.size) { + let resRC = getCoordsFromIndex(index); + let indexZ = i32(getIndices(resRC.x, resRC.z)); + let inBounds = select(0.0, 1.0, indexZ >= 0 && indexZ < uniforms.aShape[2]); + setOutputAtIndex(index, inBounds * getA(${e})); + } + } + `}}function Ioe(n){const e=["resRC.x","resRC.y","resRC.z","resRC.w"],t=[];for(let s=0;st.disposeData(R.dataId)),t.makeTensorInfo(c.outputShape,E.dtype,E.values)}const x=new Toe(d.shape,f),m=t.runWebGPUProgram(x,[d,p],d.dtype);h.push(m);const g=tt({inputs:{x:m},backend:t,attrs:{shape:c.outputShape}});return h.forEach(v=>t.disposeData(v.dataId)),g}const Eoe={kernelName:bd,backendName:"webgpu",kernelFunc:Mk};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const koe=xs({opType:bt.GREATER,cpuKernelImpl:zne,dtype:"bool"}),Aoe={kernelName:yd,backendName:"webgpu",kernelFunc:koe};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Roe=xs({opType:bt.GREATER_EQUAL,dtype:"bool",cpuKernelImpl:One}),Moe={kernelName:mu,backendName:"webgpu",kernelFunc:Roe};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Noe(n){const{inputs:e,backend:t}=n,{input:s}=e;return Rk(s,!0,t)}const $oe={kernelName:V0,backendName:"webgpu",kernelFunc:Noe};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Doe=jt({opType:Me.IS_FINITE,dtype:"bool"}),Poe={kernelName:xu,backendName:"webgpu",kernelFunc:Doe};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Loe=jt({opType:Me.IS_INF,dtype:"bool"}),Foe={kernelName:vu,backendName:"webgpu",kernelFunc:Loe};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ooe=jt({opType:Me.IS_NAN,dtype:"bool"}),zoe={kernelName:bu,backendName:"webgpu",kernelFunc:Ooe};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Boe(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{alpha:i}=s,o=[{type:"float32",data:[i]}],a=new rh(r.shape,Me.LEAKYRELU,"alpha : f32,");return t.runWebGPUProgram(a,[r],"float32",o)}const Uoe={kernelName:wd,backendName:"webgpu",kernelFunc:Boe};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Voe=xs({opType:bt.LESS,dtype:"bool",cpuKernelImpl:Une}),Woe={kernelName:Sd,backendName:"webgpu",kernelFunc:Voe};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Goe=xs({opType:bt.LESS_EQUAL,dtype:"bool",cpuKernelImpl:Bne}),Hoe={kernelName:Cd,backendName:"webgpu",kernelFunc:Goe};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class qoe{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="start : f32, step : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="linSpace"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + setOutputAtIndex(index, uniforms.start + f32(index) * uniforms.step); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Xoe(n){const{backend:e,attrs:t}=n,{start:s,stop:r,num:i}=t,o=(r-s)/(i-1),a=new qoe(i),l=[{type:"float32",data:[s]},{type:"float32",data:[o]}];return e.runWebGPUProgram(a,[],"float32",l)}const Koe={kernelName:p2,backendName:"webgpu",kernelFunc:Xoe};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const joe=jt({opType:Me.LOG,cpuKernelImpl:Vne}),Yoe={kernelName:yu,backendName:"webgpu",kernelFunc:joe};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Zoe=jt({opType:Me.LOG1P}),Joe={kernelName:wu,backendName:"webgpu",kernelFunc:Zoe};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qoe=xs({opType:bt.LOGICAL_AND,dtype:"bool"}),eae={kernelName:_d,backendName:"webgpu",kernelFunc:Qoe};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tae=jt({opType:Me.LOGICAL_NOT}),nae={kernelName:Td,backendName:"webgpu",kernelFunc:tae};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const sae=xs({opType:bt.LOGICAL_OR}),rae={kernelName:Id,backendName:"webgpu",kernelFunc:sae};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Nk=` + var powValue = 0.0; + let basis = uniforms.bias + uniforms.alpha * sum; + if (uniforms.beta == 0.5) { + powValue = inverseSqrt(basis); + } else if (uniforms.beta == 1.0) { + powValue = 1.0 / basis; + } else { + powValue = exp(log(basis) * (-uniforms.beta)); + } +`;class iae{constructor(e){this.outputShape=[],this.variableNames=["x"],this.uniforms="radius : i32, bias : f32, alpha : f32, beta : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="lrn"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let b = coords[0]; + let r = coords[1]; + let c = coords[2]; + let d = coords[3]; + + let x = getX(b, r, c, d); + var sum = 0.0; + for (var i = -uniforms.radius; i <= uniforms.radius; i = i + 1) { + let idx = d + i; + if (idx >= 0 && idx < uniforms.xShape[3]) { + let z = getX(b, r, c, idx); + sum = sum + z * z; + } + } + ${Nk} + + setOutputAtIndex(index, x * powValue); + } + } + `}}class oae{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.uniforms="radius : i32, bias : f32, alpha : f32, beta : f32,",this.workgroupSize=[256,1,1],this.maxAllowRadius=16,N(t<=this.maxAllowRadius,()=>`Radius must be less than or equal to ${this.maxAllowRadius}, current radius is ${t}`),this.outputShape=e,this.elementsPerWorkgroup=this.workgroupSize[0]-2*this.maxAllowRadius,this.dispatchLayout={x:[3],y:[2],z:[0,1]},this.dispatch=Le(this.dispatchLayout,this.outputShape,[this.elementsPerWorkgroup,this.workgroupSize[1],this.workgroupSize[2]]),this.shaderKey="lrn_shared"}getUserCode(){return` + var lrnSub: array; + const elementsPerWorkgroup = ${this.elementsPerWorkgroup}; + const maxAllowRadius = ${this.maxAllowRadius}; + + ${De()} { + let localDepth = i32(localId.x); + let workgroupDepth = i32(workgroupId.x) * elementsPerWorkgroup; + let xDepth = workgroupDepth + localDepth - maxAllowRadius; + let b = i32(globalId.z) / uniforms.xShape[1]; + let r = i32(globalId.z) - b * uniforms.xShape[1]; + let c = i32(globalId.y); + let d = workgroupDepth + localDepth; + + var x = 0.0; + if (xDepth >= 0 && xDepth < uniforms.xShape[3]) { + x = getX(b, r, c, xDepth); + } + lrnSub[localDepth] = x; + workgroupBarrier(); + + if (localDepth < elementsPerWorkgroup && d < uniforms.outShape[3]) { + var sum = 0.0; + let index = localDepth + maxAllowRadius; + for (var i = -uniforms.radius; i <= uniforms.radius; i = i + 1) { + let z = lrnSub[index + i]; + sum = sum + z * z; + } + ${Nk} + + setOutputAtCoords(b, r, c, d, lrnSub[index] * powValue); + } + } `}}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function aae(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{depthRadius:i,bias:o,alpha:a,beta:l}=s;let c;i>16?c=new iae(r.shape):c=new oae(r.shape,i);const u=[{type:"int32",data:[i]},{type:"float32",data:[o]},{type:"float32",data:[a]},{type:"float32",data:[l]}];return t.runWebGPUProgram(c,[r],r.dtype,u)}const lae={kernelName:Ed,backendName:"webgpu",kernelFunc:aae};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class cae{constructor(e){this.outputShape=[],this.variableNames=["inputImage","outputImage","dy"],this.uniforms="depthRadius : i32, bias : f32, alpha : f32, beta : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="lrn_grad"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let b = coords[0]; + let r = coords[1]; + let c = coords[2]; + + let MIN_DEPTH_BEGIN = 0; + let MAX_DEPTH_END = uniforms.outShape[3]; + var result = 0.0; + for (var d = MIN_DEPTH_BEGIN; d < MAX_DEPTH_END; d++) { + let depthBegin = max(MIN_DEPTH_BEGIN, d - uniforms.depthRadius); + let depthEnd = min(MAX_DEPTH_END, d + uniforms.depthRadius + 1); + + var norm = 0.0; + for (var k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; k++) { + if (k < depthBegin) { + continue; + } else if (k >= depthBegin && k < depthEnd) { + norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k); + } else { + break; + } + } + + norm = uniforms.alpha * norm + uniforms.bias; + + for (var k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; k++) { + if (k < depthBegin) { + continue; + } else if (k >= depthBegin && k < depthEnd) { + var dyi = -2.0 * uniforms.alpha * uniforms.beta + * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d) / norm; + if (k == d) { + dyi += pow(norm, -1.0 * uniforms.beta); + } + if (k == coords[3]) { + dyi *= getDy(b, r, c, d); + result += dyi; + } + } else { + break; + } + } + } + + setOutputAtIndex(index, result); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function uae(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,y:i,dy:o}=e,{depthRadius:a,bias:l,alpha:c,beta:u}=s,h=new cae(r.shape),d=[{type:"int32",data:[a]},{type:"float32",data:[l]},{type:"float32",data:[c]},{type:"float32",data:[u]}];return t.runWebGPUProgram(h,[r,i,o],r.dtype,d)}const hae={kernelName:G0,backendName:"webgpu",kernelFunc:uae};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dae=xs({opType:bt.MAX,cpuKernelImpl:Gne}),pae={kernelName:Su,backendName:"webgpu",kernelFunc:dae};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fae(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{filterSize:i,strides:o,pad:a,dimRoundingMode:l}=s,u=Rs(r.shape,i,o,1,a,l);return yk(r,u,"max",t)}const mae={kernelName:Ad,backendName:"webgpu",kernelFunc:fae};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gae(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{filterSize:i,strides:o,pad:a,dataFormat:l,dimRoundingMode:c}=s,u=[1,1,1],h=$r(r.shape,i,o,u,a,c,l),d=new ib(h,"max"),p=[{type:"int32",data:[h.strideDepth,h.strideHeight,h.strideWidth]},{type:"int32",data:[h.padInfo.front,h.padInfo.top,h.padInfo.left]},{type:"int32",data:[h.inDepth,h.inHeight,h.inWidth]},{type:"int32",data:[h.effectiveFilterDepth,h.effectiveFilterHeight,h.effectiveFilterWidth]}];return t.runWebGPUProgram(d,[r],r.dtype,p)}const xae={kernelName:Rd,backendName:"webgpu",kernelFunc:gae};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class vae{constructor(e){this.variableNames=["dy","maxPos"],this.uniforms=`strides : vec2, pads : vec2, dilations : vec2, filterDims : vec2, + outHeight : i32, outWidth : i32`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="maxPool2DBackprop"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords[0]; + let d = coords[3]; + + let dyRCCorner = vec2(coords.yz) - uniforms.pads; + let dyRCorner = dyRCCorner.x; + let dyCCorner = dyRCCorner.y; + + // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d). + // ? = to be determined. : = across all values in that axis. + var dotProd = 0.0; + let lastIndex = uniforms.filterDims[0] * uniforms.filterDims[1] - 1; + for (var wR = 0; wR < uniforms.filterDims[0]; wR += uniforms.dilations[0]) { + let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]); + + if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) { + continue; + } + let idyR = i32(dyR); + + for (var wC = 0; wC < uniforms.filterDims[1]; wC += uniforms.dilations[1]) { + let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]); + + if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) { + continue; + } + let idyC = i32(dyC); + + let dyValue = getDy(batch, idyR, idyC, d); + let maxPosValue = lastIndex - i32(getMaxPos(batch, idyR, idyC, d)); + + // Get the current value, check it against the value from the + // position matrix. + let curPosValue = wR * uniforms.filterDims[1] + wC; + let mask = select(0.0, 1.0, maxPosValue == curPosValue); + dotProd += dyValue * mask; + } + } + setOutputAtIndex(index, dotProd); + } + } + `}}class bae{constructor(e){this.variableNames=["dy","maxPos"],this.uniforms=`strides : vec3, pads : vec3, filterDims : vec3, + outDepth : i32, outHeight : i32, outWidth : i32`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="maxPool3DBackprop"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let batch = coords.x; + let ch = coords.u; + + let dyCorner = vec3(coords.y, coords.z, coords.w) - uniforms.pads; + let dyDCorner = dyCorner.x; + let dyRCorner = dyCorner.y; + let dyCCorner = dyCorner.z; + + // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get + // dx(xD, xR, xC, ch). + // ? = to be determined. : = across all values in that axis. + var dotProd = 0.0; + let lastIndex = uniforms.filterDims[0] * uniforms.filterDims[1] * uniforms.filterDims[2] - 1; + + for (var wD = 0; wD < uniforms.filterDims[0]; wD++) { + let dyD = f32(dyDCorner + wD) / f32(uniforms.strides[0]); + + if (dyD < 0.0 || dyD >= f32(uniforms.outDepth) || fract(dyD) > 0.0) { + continue; + } + let idyD = i32(dyD); + + for (var wR = 0; wR < uniforms.filterDims[1]; wR++) { + let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]); + + if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) { + continue; + } + let idyR = i32(dyR); + + for (var wC = 0; wC < uniforms.filterDims[2]; wC++) { + let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]); + + if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) { + continue; + } + let idyC = i32(dyC); + + let dyValue = getDy(batch, idyD, idyR, idyC, ch); + let maxPosValue = lastIndex - i32(getMaxPos(batch, idyD, idyR, idyC, ch)); + + // Get the current value, check it against the value from the + // position matrix. + let curPosValue = wD * uniforms.filterDims[1] * uniforms.filterDims[2] + wR * uniforms.filterDims[2] + wC; + let mask = select(0.0, 1.0, maxPosValue == curPosValue); + dotProd += dyValue * mask; + } + } + } + + setOutputAtIndex(index, dotProd); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function yae(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:i}=e,o=i,{filterSize:a,strides:l,pad:c,dimRoundingMode:u}=s,h=[1,1,1],d=$r(o.shape,a,l,h,c,u),p=new ib(d,"max",!0);let f=[{type:"int32",data:[d.strideDepth,d.strideHeight,d.strideWidth]},{type:"int32",data:[d.padInfo.front,d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.inDepth,d.inHeight,d.inWidth]},{type:"int32",data:[d.effectiveFilterDepth,d.effectiveFilterHeight,d.effectiveFilterWidth]}];const x=t.runWebGPUProgram(p,[o],"int32",f),m=new bae(d);f=[{type:"int32",data:[d.strideDepth,d.strideHeight,d.strideWidth]},{type:"int32",data:[d.effectiveFilterDepth-1-d.padInfo.front,d.effectiveFilterHeight-1-d.padInfo.top,d.effectiveFilterWidth-1-d.padInfo.left]},{type:"int32",data:[d.effectiveFilterDepth,d.effectiveFilterHeight,d.effectiveFilterWidth]},{type:"int32",data:[d.outDepth]},{type:"int32",data:[d.outHeight]},{type:"int32",data:[d.outWidth]}];const g=t.runWebGPUProgram(m,[r,x],o.dtype,f);return t.disposeData(x.dataId),g}const wae={kernelName:q0,backendName:"webgpu",kernelFunc:yae};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Sae(n){const{inputs:e,backend:t,attrs:s}=n,{dy:r,input:i,output:o}=e,a=i;fk([i,o],"maxPoolGrad");const{filterSize:l,strides:c,pad:u,dimRoundingMode:h}=s,d=Rs(a.shape,l,c,1,u,h),p=new Yh(d,"max",!0);let f=[{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.dilationHeight,d.dilationWidth]},{type:"int32",data:[d.inHeight,d.inWidth]},{type:"int32",data:[d.effectiveFilterHeight,d.effectiveFilterWidth]}];const x=t.runWebGPUProgram(p,[a],"int32",f),m=new vae(d);f=[{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.effectiveFilterHeight-1-d.padInfo.top,d.effectiveFilterWidth-1-d.padInfo.left]},{type:"int32",data:[d.dilationHeight,d.dilationWidth]},{type:"int32",data:[d.effectiveFilterHeight,d.effectiveFilterWidth]},{type:"int32",data:[d.outHeight]},{type:"int32",data:[d.outWidth]}];const g=t.runWebGPUProgram(m,[r,x],a.dtype,f);return t.disposeData(x.dataId),g}const Cae={kernelName:H0,backendName:"webgpu",kernelFunc:Sae};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _ae(n){const{inputs:e,backend:t,attrs:s}=n,{filterSize:r,strides:i,pad:o,includeBatchInIndex:a}=s,{x:l}=e;N(l.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${l.shape.length}.`);const c=[1,1];N(gs(i,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);const u=Rs(l.shape,r,i,c,o),h=[{type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[u.inHeight,u.inWidth]},{type:"int32",data:[u.effectiveFilterHeight,u.effectiveFilterWidth]}];let d=new Yh(u,"max",!1);const p=t.runWebGPUProgram(d,[l],l.dtype,h);d=new Yh(u,"max",!0,!0,a);const f=t.runWebGPUProgram(d,[l],"int32",h);return[p,f]}const Tae={kernelName:f2,backendName:"webgpu",kernelFunc:_ae};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Iae(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i,keepDims:o}=s;return Hl(r,i,o,"min",t)}const Eae={kernelName:Nd,backendName:"webgpu",kernelFunc:Iae};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kae=xs({opType:bt.MIN,cpuKernelImpl:Hne}),Aae={kernelName:Cu,backendName:"webgpu",kernelFunc:kae};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Rae{constructor(e,t,s){this.uniforms="",this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((r,i)=>r[0]+e[i]+r[1]),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.xShape=e,t.map((r,i)=>{this.uniforms+=` pad${i} : vec2,`}),this.offset=s==="reflect"?0:1,this.shaderKey=`mirrorPad_${s}`}getUserCode(){const e=this.xShape.length,t=this.xShape.map((c,u)=>`uniforms.pad${u}[0]`).join(","),s=this.xShape.map((c,u)=>`uniforms.pad${u}[0] + uniforms.xShape${e>1?`[${u}]`:""}`).join(","),r=e===1?"start":"start[i]",i=e===1?"end":"end[i]",o=e===1?"outC":"outC[i]",a=zn(e),l=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return` + ${De("index")} { + if (index < uniforms.size) { + let start = ${a}(${t}); + let end = ${a}(${s}); + var outC = getCoordsFromIndex(index); + for (var i = 0; i < ${e}; i = i + 1) { + if (${o} < ${r}) { + ${o} = ${r} * 2 - ${o} - ${this.offset}; + } else if(${o} >= ${i}) { + ${o} = (${i} - 1) * 2 - ${o} + ${this.offset}; + } + } + let coords = outC - start; + setOutputAtIndex(index, getX(${l})); + } + } + `}}/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Mae={kernelName:$d,backendName:"webgpu",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{x:s}=n,{paddings:r,mode:i}=e,o=t,a=r.map(u=>({type:"int32",data:[u[0],u[1]]})),l=new Rae(s.shape,r,i);return o.runWebGPUProgram(l,[s],s.dtype,a)}};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Nae=xs({opType:bt.MOD}),$ae={kernelName:_u,backendName:"webgpu",kernelFunc:Nae};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Dae{constructor(e,t){this.variableNames=["probs"],this.outputShape=[],this.uniforms="seed : f32, numOutcomes: i32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e,t],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="multinomial"}getUserCode(){return` + //Based on the work of Dave Hoskins + //https://www.shadertoy.com/view/4djSRW + fn random (seed : f32, resultUV : vec2) -> f32 { + let HASHSCALE1 = 443.8975; + let p = resultUV * seed; + var p3 = fract(vec3(p.xyx) * HASHSCALE1); + p3 = p3 + dot(p3, p3.yzx + 19.19); + return fract((p3.x + p3.y) * p3.z); + } + + ${De("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let batch = coords[0]; + + let resUV = vec2(f32(coords[1]) / f32(uniforms.outShape[1]), + f32(coords[0]) / f32(uniforms.outShape[0])); + let r = random(uniforms.seed, resUV); + var cdf = 0.0; + for (var i = 0; i < uniforms.numOutcomes - 1; i = i + 1) { + cdf = cdf + getProbs(batch, i); + + if (r < cdf) { + setOutputAtIndexI32(index, i); + return; + } + } + + // If no other event happened, last event happened. + setOutputAtIndexI32(index, uniforms.numOutcomes - 1); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Pae{constructor(e){this.variableNames=["logits"],this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=[this.outputShape[0],1,1],this.outputShape[1]>=4096?this.workgroupSize=[256,1,1]:this.workgroupSize=[64,1,1],this.shaderKey="softmax"}getUserCode(){return` + var buf : array; + var rowMaxShared : f32; + var rowSumShared : f32; + const blockSize = ${this.workgroupSize[0]}; + ${De("index")} { + let row = index / blockSize; + let tid = i32(localId.x); + let cols = uniforms.outShape[1]; + + var threadMax = -3.402823e+38f; + for (var col = tid; col < cols; col += blockSize) { + let value = getLogits(row, col); + threadMax = max(threadMax, value); + } + if (tid < cols) { + buf[tid] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, blockSize); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (tid < currSize) { + buf[tid] = max(buf[tid], buf[tid + reduceSize]); + } + workgroupBarrier(); + } + + if (tid == 0) { + rowMaxShared = buf[0]; + } + workgroupBarrier(); + + var threadSum = 0.0; + for (var col = tid; col < cols; col += blockSize) { + let subExp = exp(getLogits(row, col) - rowMaxShared); + threadSum += subExp; + } + buf[tid] = threadSum; + workgroupBarrier(); + + for (var currSize = blockSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (tid < currSize) { + buf[tid] = buf[tid] + buf[tid + currSize]; + } + workgroupBarrier(); + } + + if (tid == 0) { + rowSumShared = buf[0]; + } + workgroupBarrier(); + + for (var col = tid; col < cols; col += blockSize) { + let value = exp(getLogits(row, col) - rowMaxShared) / rowSumShared; + setOutputAtCoords(row, col, value); + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $k(n){const{inputs:e,backend:t,attrs:s}=n,{logits:r}=e,{dim:i}=s,o=tt({inputs:{x:r},backend:t,attrs:{shape:[re(r.shape)/r.shape[i],r.shape[i]]}}),a=new Pae(o.shape),l=t.runWebGPUProgram(a,[o],r.dtype),c=tt({inputs:{x:l},backend:t,attrs:{shape:r.shape}});return t.disposeData(o.dataId),t.disposeData(l.dataId),c}const Lae={kernelName:Zd,backendName:"webgpu",kernelFunc:$k};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Fae(n){const{inputs:e,backend:t,attrs:s}=n,{logits:r}=e,{numSamples:i,seed:o,normalized:a}=s,l=a?r:$k({inputs:{logits:r},backend:t,attrs:{dim:r.shape.length-1}}),c=l.shape[0],u=l.shape[1],h=new Dae(c,i),d=[{type:"float32",data:[o]},{type:"int32",data:[u]}],p=t.runWebGPUProgram(h,[l],"int32",d);return a||t.disposeData(l.dataId),p}const Oae={kernelName:m2,backendName:"webgpu",kernelFunc:Fae};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zae(n){const{inputs:e,backend:t}=n,{x:s}=e;if(t.shouldExecuteOnCPU([s])){const i=t.tensorMap.get(s.dataId),[o,a]=Xne(i.values,s.shape,s.dtype);return t.makeTensorInfo(a,s.dtype,o)}const r=new rh(s.shape,Me.NEG);return t.runWebGPUProgram(r,[s],s.dtype)}const Bae={kernelName:Dd,backendName:"webgpu",kernelFunc:zae};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Uae(n){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:e,backend:t,attrs:s}=n,{boxes:r,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:l}=s,c=t.readSync(r.dataId),u=t.readSync(i.dataId),{selectedIndices:h}=mm(c,u,o,a,l);return t.makeTensorInfo([h.length],"int32",new Int32Array(h))}const Vae={kernelName:X0,backendName:"webgpu",kernelFunc:Uae};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Wae(n){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:e,backend:t,attrs:s}=n,{boxes:r,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:l,softNmsSigma:c}=s,u=t.readSync(r.dataId),h=t.readSync(i.dataId),d=o,p=a,f=l,x=c,{selectedIndices:m,selectedScores:g}=gm(u,h,d,p,f,x);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([g.length],"float32",new Float32Array(g))]}const Gae={kernelName:K0,backendName:"webgpu",kernelFunc:Wae};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Hae{constructor(e,t){this.variableNames=["x"],this.uniforms="onValue : f32, offValue : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e,t],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="onehot"}getUserCode(){return` + ${De("index")} { + if(index < uniforms.size) { + let coords = getCoordsFromIndex(index); + setOutputAtIndex(index, mix(uniforms.offValue, uniforms.onValue, + f32(i32(round(getX(coords.x))) == coords.y))); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qae(n){const{inputs:e,backend:t,attrs:s}=n,{indices:r}=e,{dtype:i,depth:o,onValue:a,offValue:l}=s,c=re(r.shape),u=new Hae(c,o),h=tt({inputs:{x:r},backend:t,attrs:{shape:[c]}}),d=[{type:"float32",data:[a]},{type:"float32",data:[l]}],p=t.runWebGPUProgram(u,[h],i,d);t.disposeData(h.dataId);const f=[...r.shape,o],x=tt({inputs:{x:p},backend:t,attrs:{shape:f}});return t.disposeData(p.dataId),x}const Xae={kernelName:Fd,backendName:"webgpu",kernelFunc:qae};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function o0(n){const{inputs:e,backend:t}=n,{x:s}=e;if(s.dtype==="complex64"){const r=wp({inputs:{input:s},backend:t}),i=o0({inputs:{x:r},backend:t}),o=sg({inputs:{input:s},backend:t}),a=o0({inputs:{x:o},backend:t}),l=Gl({inputs:{real:i,imag:a},backend:t});return t.disposeData(r.dataId),t.disposeData(i.dataId),t.disposeData(o.dataId),t.disposeData(a.dataId),l}else return sr({attrs:{shape:s.shape,dtype:s.dtype,value:s.dtype==="string"?"":0},backend:t})}const Kae={kernelName:ep,backendName:"webgpu",kernelFunc:o0};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Dk(n){const{inputs:e,backend:t}=n,{x:s}=e;if(s.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(s.dtype==="complex64"){const r=wp({inputs:{input:s},backend:t}),i=Dk({inputs:{x:r},backend:t}),o=sg({inputs:{input:s},backend:t}),a=o0({inputs:{x:o},backend:t}),l=Gl({inputs:{real:i,imag:a},backend:t});return t.disposeData(r.dataId),t.disposeData(i.dataId),t.disposeData(o.dataId),t.disposeData(a.dataId),l}else return sr({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:t})}const jae={kernelName:Ld,backendName:"webgpu",kernelFunc:Dk};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Yae(n){const{inputs:e,backend:t,attrs:s}=n,{axis:r}=s;if(e.length===1)return Ax({inputs:{input:e[0]},backend:t,attrs:{dim:r}});const i=e[0].shape,o=e[0].dtype;e.forEach(u=>{y0(i,u.shape,"All tensors passed to stack must have matching shapes"),N(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=[],l=e.map(u=>{const h=Ax({inputs:{input:u},backend:t,attrs:{dim:r}});return a.push(h),h}),c=Ck({inputs:l,backend:t,attrs:{axis:r}});return a.forEach(u=>t.disposeData(u.dataId)),c}const Zae={kernelName:Od,backendName:"webgpu",kernelFunc:Yae};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Pk(n,e=!1){const t=n.length,s=zn(t),r=n.map((h,d)=>`uniforms.pad${d}[0]`).join(","),i=n.map((h,d)=>`uniforms.pad${d}[0] + uniforms.xShape${t>1?`[${d}]`:""}`).join(","),o=t>1?`${s}(${r})`:`${r}`,a=t>1?`${s}(${i})`:`${i}`,l=t>1?"any(paddedCoords < start)":"paddedCoords < start",c=t>1?"any(paddedCoords >= end)":"paddedCoords >= end",u=t>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,t):"coords";return` + let start = ${o}; + let end = ${a}; + if (${l} || ${c}) { + setOutputAtIndex(index, ${e?0:"uniforms.constantValue"}); + } else { + let coords = paddedCoords - start; + setOutputAtIndex(index, getX(${u})); + } + `}class Jae{constructor(e,t){this.variableNames=["x"],this.uniforms="constantValue : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((s,r)=>s[0]+e[r]+s[1]),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),t.map((s,r)=>{this.uniforms+=` pad${r} : vec2,`}),this.xShape=e,this.shaderKey="pad"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let paddedCoords = getCoordsFromIndex(index); + ${Pk(this.xShape)} + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qae=n=>{const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{paddings:i,constantValue:o}=s;if(i.every(c=>Wt(c,[0,0])))return br({inputs:{x:r},backend:t});if(re(r.shape)===0){const c=i.map((u,h)=>u[0]+r.shape[h]+u[1]);return sr({backend:t,attrs:{shape:c,value:o,dtype:r.dtype}})}const a=[{type:"float32",data:[o]}];i.map(c=>a.push({type:"int32",data:[c[0],c[1]]}));const l=new Jae(r.shape,i);return t.runWebGPUProgram(l,[r],r.dtype,a)},ele={kernelName:zd,backendName:"webgpu",kernelFunc:Qae};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tle=xs({opType:bt.POW}),nle={kernelName:Iu,backendName:"webgpu",kernelFunc:tle};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sle(n){const{inputs:e,backend:t}=n,{x:s,alpha:r}=e,i=new r0(bt.PRELU,s.shape,r.shape);return t.runWebGPUProgram(i,[s,r],"float32")}const rle={kernelName:Bd,backendName:"webgpu",kernelFunc:sle};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ile(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{axis:i,keepDims:o}=s;return Hl(r,i,o,"prod",t)}const ole={kernelName:Ud,backendName:"webgpu",kernelFunc:ile};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ale=n=>{const{backend:e,attrs:t}=n,{start:s,stop:r,step:i,dtype:o}=t,a=Yne(s,r,i,o);return e.makeTensorInfo([a.length],o,a)},lle={kernelName:j0,backendName:"webgpu",kernelFunc:ale};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cle=xs({opType:bt.DIV}),ule={kernelName:lu,backendName:"webgpu",kernelFunc:cle};/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hle=jt({opType:Me.RECIPROCAL}),dle={kernelName:Eu,backendName:"webgpu",kernelFunc:hle};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ple=jt({opType:Me.RELU}),fle={kernelName:ku,backendName:"webgpu",kernelFunc:ple};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mle=jt({opType:Me.RELU6}),gle={kernelName:Au,backendName:"webgpu",kernelFunc:mle};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class xle{constructor(e,t,s){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2, halfPixelCenters : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,s,e[3]],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="resizeBilinear"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let b = coords[0]; + let d = coords[3]; + let rc = coords.yz; + + let effectiveInSize = vec2( + f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0], + f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]); + + let effectiveOutSize = vec2( + f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0], + f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]); + + let effectiveInputOverOutputRatioRC = + effectiveInSize / effectiveOutSize; + + // Fractional source index + let sourceFracIndexRC = + (vec2(rc) + vec2(uniforms.halfPixelCenters)) * + effectiveInputOverOutputRatioRC - vec2(uniforms.halfPixelCenters); + + // Compute the four integer indices. + let sourceFloorRC = vec2(sourceFracIndexRC); + let sourceCeilRC = vec2( + min(vec2(uniforms.xShape.yz) - vec2(1.0), ceil(sourceFracIndexRC))); + + let topLeft = getX(b, sourceFloorRC.x, sourceFloorRC.y, d); + let bottomLeft = getX(b, sourceCeilRC.x, sourceFloorRC.y, d); + let topRight = getX(b, sourceFloorRC.x, sourceCeilRC.y, d); + let bottomRight = getX(b, sourceCeilRC.x, sourceCeilRC.y, d); + + let fracRC = sourceFracIndexRC - vec2(sourceFloorRC); + + let top = topLeft + (topRight - topLeft) * fracRC.y; + let bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y; + let newValue = top + (bottom - top) * fracRC.x; + + setOutputAtIndex(index, newValue); + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vle(n){const{inputs:e,backend:t,attrs:s}=n,{images:r}=e,{alignCorners:i,size:o,halfPixelCenters:a}=s,[l,c]=o,u=i&&l>1?1:0,h=i&&c>1?1:0,p=[{type:"float32",data:[u,h]},{type:"float32",data:[a?.5:0]}],f=new xle(r.shape,l,c);return t.runWebGPUProgram(f,[r],"float32",p)}const ble={kernelName:Gd,backendName:"webgpu",kernelFunc:vle};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class yle{constructor(e,t){this.variableNames=["dy"],this.uniforms=`effectiveXSize : vec2, effectiveYSize : vec2, heightScale : f32, widthScale : f32, + invHeightScale : f32, invWidthScale : f32, winHeight : i32, winWidth : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.alignCorners=t,this.shaderKey=`resizeBilinearBackprop_${t}`}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let b = coords[0]; + let d = coords[3]; + let r = coords[1]; + let c = coords[2]; + + var accumulator = 0.0; + + // Compute bounds for where in dy we will look + let startRLerp = floor(f32(r) * uniforms.invHeightScale); + let startDyR = i32(startRLerp - f32(uniforms.winHeight / 2)); + + let startCLerp = floor(f32(c) * uniforms.invWidthScale); + let startDyC = i32(startCLerp - f32(uniforms.winWidth / 2)); + + // Loop over dy + for (var dyROffset = 0; dyROffset < uniforms.winHeight; dyROffset++) { + let dyR = startDyR + dyROffset; + + // Guard against the window exceeding the bounds of dy + if (dyR < 0 || dyR >= uniforms.dyShape[1]) { + continue; + } + + for (var dyCOffset = 0; dyCOffset < uniforms.winWidth; dyCOffset++) { + let dyC = startDyC + dyCOffset; + + // Guard against the window exceeding the bounds of dy + if (dyC < 0 || dyC >= uniforms.dyShape[2]) { + continue; + } + + let dxR = f32(dyR) * uniforms.heightScale; + let topDxRIndex = i32(floor(dxR)); + let bottomDxRIndex = i32(min(ceil(dxR), f32(uniforms.outShape[1] - 1))); + let dxRLerp = dxR - f32(topDxRIndex); + let inverseDxRLerp = 1.0 - dxRLerp; + + let dxC = f32(dyC) * uniforms.widthScale; + let leftDxCIndex = i32(floor(dxC)); + let rightDxCIndex = i32(min(ceil(dxC), f32(uniforms.outShape[2] - 1))); + let dxCLerp = dxC - f32(leftDxCIndex); + let inverseDxCLerp = 1.0 - dxCLerp; + + if (r == topDxRIndex && c == leftDxCIndex) { + // topLeft + accumulator += + getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp; + } + + if (r == topDxRIndex && c == rightDxCIndex) { + // topRight + accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp; + } + + if (r == bottomDxRIndex && c == leftDxCIndex) { + // bottomLeft + accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp; + } + + if (r == bottomDxRIndex && c == rightDxCIndex) { + // bottomRight + accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp; + } + } + } + // End loop over dy + + setOutputAtIndex(index, accumulator); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function wle(n){const{inputs:e,backend:t,attrs:s}=n,{images:r,dy:i}=e,{alignCorners:o}=s,[,a,l]=r.shape,[,c,u]=i.shape,h=[o&&c>1?a-1:a,o&&u>1?l-1:l],d=[o&&c>1?c-1:c,o&&u>1?u-1:u],p=h[0]/d[0],f=h[1]/d[1],x=1/p,m=1/f,g=Math.ceil(x)*2+2,v=Math.ceil(m)*2+2,b=new yle(r.shape,o),y=[{type:"int32",data:h},{type:"int32",data:d},{type:"float32",data:[p]},{type:"float32",data:[f]},{type:"float32",data:[x]},{type:"float32",data:[m]},{type:"int32",data:[g]},{type:"int32",data:[v]}];return t.runWebGPUProgram(b,[i],i.dtype,y)}const Sle={kernelName:J0,backendName:"webgpu",kernelFunc:wle};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Cle{constructor(e,t,s,r){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2, roundBase : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,s,e[3]],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.halfPixelCenters=r,this.shaderKey=`resizeNearest_${r}`}getUserCode(){let e;return this.halfPixelCenters?e="max((vec2(rc) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":e="vec2(rc) * effectiveInputOverOutputRatioRC",` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let b = coords[0]; + let d = coords[3]; + let rc = coords.yz; + + let effectiveInSize = vec2( + f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0], + f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]); + + let effectiveOutSize = vec2( + f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0], + f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]); + + let effectiveInputOverOutputRatioRC = + effectiveInSize / effectiveOutSize; + + // Fractional source index + let sourceFracIndexRC = ${e}; + + // Compute the coordinators of nearest neighbor point. + let inputShapeRC = vec2(f32(uniforms.xShape.y), f32(uniforms.xShape.z)); + let sourceNearestRC = vec2( + min(inputShapeRC - 1.0, floor(sourceFracIndexRC + uniforms.roundBase))); + let newValue = getX(b, sourceNearestRC.x, sourceNearestRC.y, d); + + setOutputAtIndex(index, newValue); + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function _le(n){const{inputs:e,backend:t,attrs:s}=n,{images:r}=e,{alignCorners:i,halfPixelCenters:o,size:a}=s,[l,c]=a,u=i&&l>1?1:0,h=i&&c>1?1:0,p=[{type:"float32",data:[u,h]},{type:"float32",data:[i?.5:0]}],f=new Cle(r.shape,l,c,o);return t.runWebGPUProgram(f,[r],r.dtype,p)}const Tle={kernelName:Wd,backendName:"webgpu",kernelFunc:_le};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ile{constructor(e,t){this.variableNames=["dy"],this.uniforms=`effectiveXSize : vec2, effectiveYSize : vec2, invHeightScale : f32, invWidthScale : f32, + winHeight : i32, winWidth : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.alignCorners=t,this.shaderKey=`resizeNearestNeigborBackprop_${t}`}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getOutputCoords(); + let b = coords[0]; + let d = coords[3]; + let r = coords[1]; + let c = coords[2]; + + var accumulator = 0.0; + + // Compute bounds for where in dy we will look + let startRLerp = floor(f32(r) * uniforms.invHeightScale); + let startDyR = i32(floor(startRLerp - f32(uniforms.winHeight / 2))); + + let startCLerp = floor(f32(c) * uniforms.invWidthScale); + let startDyC = i32(floor(startCLerp - f32(uniforms.winWidth / 2))); + + // Loop over dy + for (var dyROffset = 0; dyROffset < uniforms.winHeight; dyROffset++) { + let dyR = startDyR + dyROffset; + + // Guard against the window exceeding the bounds of dy + if (dyR < 0 || dyR >= uniforms.dyShape[1]) { + continue; + } + + for (var dyCOffset = 0; dyCOffset < uniforms.winWidth; dyCOffset++) { + let dyC = startDyC + dyCOffset; + + // Guard against the window exceeding the bounds of dy + if (dyC < 0 || dyC >= uniforms.dyShape[2]) { + continue; + } + + let sourceFracRow = f32(uniforms.effectiveXSize[0]) * + (f32(dyR) / f32(uniforms.effectiveYSize[0])); + + let sourceFracCol = f32(uniforms.effectiveXSize[1]) * + (f32(dyC) / f32(uniforms.effectiveYSize[1])); + + let sourceNearestRow = + i32(min(f32(uniforms.outShape[1] - 1), + ${this.alignCorners?"floor(sourceFracRow + 0.5)":"floor(sourceFracRow)"})); + + let sourceNearestCol = + i32(min(f32(uniforms.outShape[2] - 1), + ${this.alignCorners?"floor(sourceFracCol + 0.5)":"floor(sourceFracCol)"})); + + if (r == sourceNearestRow && c == sourceNearestCol) { + accumulator += getDy(b, dyR, dyC, d); + } + } + } + // End loop over dy + + setOutputAtIndex(index, accumulator); + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ele(n){const{inputs:e,backend:t,attrs:s}=n,{images:r,dy:i}=e,{alignCorners:o}=s,[,a,l]=r.shape,[,c,u]=i.shape,h=[o&&c>1?a-1:a,o&&u>1?l-1:l],d=[o&&c>1?c-1:c,o&&u>1?u-1:u],p=h[0]/d[0],f=h[1]/d[1],x=1/p,m=1/f,g=Math.ceil(x)*2+2,v=Math.ceil(m)*2+2,b=new Ile(r.shape,o),y=[{type:"int32",data:h},{type:"int32",data:d},{type:"float32",data:[x]},{type:"float32",data:[m]},{type:"int32",data:[g]},{type:"int32",data:[v]}];return t.runWebGPUProgram(b,[i],i.dtype,y)}const kle={kernelName:Z0,backendName:"webgpu",kernelFunc:Ele};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ale{constructor(e){this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms=" axis : vec4,",this.shaderKey="reverse"}getUserCode(){return` + + // Using uniform variables as judging conditions, so the function has + // coherent execution within all threads. + fn getReverseCoords(coords : vec4) -> vec4 { + var reverseCoords = coords; + if (uniforms.axis[0] == 1) { + reverseCoords[0] = uniforms.xShape[0] - coords[0] - 1; + } + if (uniforms.axis[1] == 1) { + reverseCoords[1] = uniforms.xShape[1] - coords[1] - 1; + } + if (uniforms.axis[2] == 1) { + reverseCoords[2] = uniforms.xShape[2] - coords[2] - 1; + } + if (uniforms.axis[3] == 1) { + reverseCoords[3] = uniforms.xShape[3] - coords[3] - 1; + } + + return reverseCoords; + } + + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let reverseCoords = getReverseCoords(coords); + setOutputAtIndex(index, getX(reverseCoords[0], + reverseCoords[1], reverseCoords[2], reverseCoords[3])); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Rle(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{dims:i}=s,o=r.shape.length;if(o===0)return br({inputs:{x:r},backend:t});const a=r.shape,l=[1,1,1,1];a.forEach((m,g)=>{const v=g+4-o;l[v]=m});const c=It(i,r.shape),u=[0,0,0,0];c.forEach(m=>{const g=m+4-o;u[g]=1});const h=[{type:"int32",data:u}],d=tt({inputs:{x:r},backend:t,attrs:{shape:l}}),p=new Ale(l),f=t.runWebGPUProgram(p,[d],d.dtype,h);t.disposeData(d.dataId);const x=tt({inputs:{x:f},backend:t,attrs:{shape:a}});return t.disposeData(f.dataId),x}const Mle={kernelName:Hd,backendName:"webgpu",kernelFunc:Rle};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Nle{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms=`centerX : f32, centerY : f32, sinRadians : f32, + cosRadians : f32,`,this.shaderKey="rotate",this.outputShape=e,typeof t=="number"?(this.uniforms+=" fillValue : f32,",this.fillSnippet="var outputValue = uniforms.fillValue;",this.shaderKey+="_float"):(this.uniforms+=" fillValue : vec3,",this.fillSnippet="var outputValue = uniforms.fillValue[coords[3]];",this.shaderKey+="_vec3")}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let coordXFloat = (f32(coords[2]) - uniforms.centerX) * + uniforms.cosRadians - (f32(coords[1]) - uniforms.centerY) * + uniforms.sinRadians; + let coordYFloat = (f32(coords[2]) - uniforms.centerX) * + uniforms.sinRadians + (f32(coords[1]) - uniforms.centerY) * + uniforms.cosRadians; + let coordX = i32(round(coordXFloat + uniforms.centerX)); + let coordY = i32(round(coordYFloat + uniforms.centerY)); + ${this.fillSnippet} + if(coordX >= 0 && coordX < uniforms.xShape[2] && coordY >= 0 && + coordY < uniforms.xShape[1]) { + outputValue = getX(coords[0], coordY, coordX, coords[3]); + } + setOutputAtIndex(index, outputValue); + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $le={kernelName:sm,backendName:"webgpu",kernelFunc:({inputs:n,attrs:e,backend:t})=>{const{image:s}=n,{radians:r,fillValue:i,center:o}=e,a=t,l=new Nle(s.shape,i),[c,u]=wm(o,s.shape[1],s.shape[2]),h=[{type:"float32",data:[c]},{type:"float32",data:[u]},{type:"float32",data:[Math.sin(r)]},{type:"float32",data:[Math.cos(r)]}];return typeof i=="number"?h.push({type:"float32",data:[Number.parseFloat(i.toFixed(2))]}):h.push({type:"float32",data:i}),a.runWebGPUProgram(l,[s],s.dtype,h)}};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Dle=jt({opType:Me.ROUND}),Ple={kernelName:Ru,backendName:"webgpu",kernelFunc:Dle};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Lle=jt({opType:Me.RSQRT,cpuKernelImpl:Zne}),Fle={kernelName:Mu,backendName:"webgpu",kernelFunc:Lle};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class $h{constructor(e,t,s,r,i,o,a,l=!0){this.variableNames=["updates","indices"],this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=o,this.type=a,this.sumDupeIndices=l,this.dispatchLayout=Xe(e),this.dispatch=Le(this.dispatchLayout,e,this.workgroupSize),this.sliceDimGreaterThanOne=t>1,this.shaderKey=`scatter_${s}_${r}_${this.sliceDimGreaterThanOne}_${a}_${l}_${i.length}`;const c=zn(i.length);this.uniforms=`sliceDim : i32, strides: ${c}, updatesSize: i32,`,this.updatesRank=r,this.indicesRank=s}getUserCode(){let e="";this.indicesRank===1?e="coords[0]":this.indicesRank===2&&(e="coords[0], j");const t=`getIndices(${e})`,s=this.sliceDimGreaterThanOne?"uniforms.strides[j]":"uniforms.strides";let r="",i="";this.dispatchLayout.x.length===1?(r="flattenedIndex",i=` + fn getUpdatesCoordsFromFlatIndex(index : i32) -> i32 { + return index; + } + `):this.dispatchLayout.x.length===2&&(r="vec2(flattenedIndex, coords[1])",i=` + fn getUpdatesCoordsFromFlatIndex(index : i32) -> vec2 { + // N.B. |updates| could be a scalar tensor, conceptually representing a + // 2D tensor with all values equal to that. By design, its size must be + // the same as |outShape[1]| in one dimension, and |indicesShape[0]| + // gives the other. + let sliceSize = uniforms.outShape[1]; + let d0 = index / sliceSize; + let d1 = index - d0 * sliceSize; + return vec2(d0, d1); + } + `);const a=`getUpdates(${Array.from({length:this.updatesRank},(c,u)=>`coords[${u}]`).join(", ")})`;return` + ${i} + ${De("index")} { + if (index < uniforms.updatesSize) { + let coords = getUpdatesCoordsFromFlatIndex(index); + var flattenedIndex = 0; + for (var j = 0; j < uniforms.sliceDim; j = j + 1) { + let indexInside = i32(round(${t})); + flattenedIndex = flattenedIndex + indexInside * ${s}; + } + let updateValue = + ${Ya(this.type)}(${a}); + let flatIndex = getOutputIndexFromCoords(${r}); + + ${this.sumDupeIndices?Aa("&result[flatIndex]","updateValue",this.type):"atomicStore(&result[flatIndex], bitcast(updateValue));"} + } + }`}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ole(n){const{inputs:e,backend:t,attrs:s}=n,{indices:r,updates:i}=e,{shape:o}=s,{sliceRank:a,numUpdates:l,sliceSize:c,strides:u,outputSize:h}=so(i,r,o),d=[h/c,c];if(h===0)return t.makeTensorInfo(o,r.dtype);const p=tt({inputs:{x:r},backend:t,attrs:{shape:[l,a]}}),f=tt({inputs:{x:i},backend:t,attrs:{shape:[l,c]}}),x=f.dtype,m=sr({backend:t,attrs:{shape:d,value:0,dtype:x}}),g=re(f.shape),v=[{type:"int32",data:[a]},{type:"int32",data:u},{type:"int32",data:[g]}],b=new $h(f.shape,a,p.shape.length,f.shape.length,u,d,x),y=t.runWebGPUProgram(b,[f,p],x,v,m),w=tt({inputs:{x:y},backend:t,attrs:{shape:o}});return t.disposeData(p.dataId),t.disposeData(f.dataId),t.disposeData(y.dataId),w}const zle={kernelName:x2,backendName:"webgpu",kernelFunc:Ole};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ble{constructor(e,t){this.outputShape=[],this.variableNames=["sortedSequence","values"],this.uniforms="numInputs : i32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.side=t,this.shaderKey=`search_sorted_${t}`}getUserCode(){return` + fn findBound(batch: i32, value: f32) -> i32 { + var left = i32(0); + var right = uniforms.numInputs; + while (left < right) { + var mid = (left + right) / 2; + if (getSortedSequence(batch, mid) ${this.side==="left"?"<":"<="} value) { + left = mid + 1; + } else { + right = mid; + } + } + return right; + } + + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let value = getValuesByOutputIndex(index); + setOutputAtIndexI32(index, findBound(coords[0], value)); + } + } + `}}/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ule(n){const{inputs:e,backend:t,attrs:s}=n,{sortedSequence:r,values:i}=e,{side:o}=s,a=new Ble([i.shape[0],i.shape[1]],o),l=[{type:"int32",data:[r.shape[1]]}];return t.runWebGPUProgram(a,[r,i],"int32",l)}const Vle={kernelName:b2,backendName:"webgpu",kernelFunc:Ule};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Wle{constructor(e,t,s){this.variableNames=["c","a","b"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.cRank=e,this.rank=s,this.shaderKey="select"}getUserCode(){let e,t;if(this.rank>4)throw Error(`Where for rank ${this.rank} is not yet supported`);if(this.rank===1)t="resRC",e="resRC";else{const r=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],o=[];for(let a=0;a= 1.0) { + setOutputAtIndex(index, getA(${t})); + } else { + setOutputAtIndex(index, getB(${t})); + } + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Gle(n){const{inputs:e,backend:t}=n,{condition:s,t:r,e:i}=e,o=new Wle(s.shape.length,r.shape,r.shape.length);return t.runWebGPUProgram(o,[s,r,i],ds(r.dtype,i.dtype))}const Hle={kernelName:qd,backendName:"webgpu",kernelFunc:Gle};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qle=jt({opType:Me.SELU}),Xle={kernelName:Nu,backendName:"webgpu",kernelFunc:qle};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Kle=jt({opType:Me.SIGMOID}),jle={kernelName:Lu,backendName:"webgpu",kernelFunc:Kle};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Yle=jt({opType:Me.SIGN}),Zle={kernelName:Pu,backendName:"webgpu",kernelFunc:Yle};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Jle=jt({opType:Me.SIN}),Qle={kernelName:$u,backendName:"webgpu",kernelFunc:Jle};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ece=jt({opType:Me.SINH}),tce={kernelName:Du,backendName:"webgpu",kernelFunc:ece};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nce=jt({opType:Me.SOFTPLUS}),sce={kernelName:Fu,backendName:"webgpu",kernelFunc:nce};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class rce{constructor(e,t,s,r,i,o){this.variableNames=["x"],this.outputShape=[],this.uniforms="",this.workgroupSize=[64,1,1],this.size=!0;const a=new Array(r.length);for(let l=0;l{this.uniforms+=` pad${c} : vec2,`}),this.shaderKey=`spaceToBatchND_${i}`}getUserCode(){const e=zn(this.outputShape.length),t=gk(this.newDim);return` + ${Tf(this.paddedXShape,"PaddedX")} + ${De("index")} { + if(index < uniforms.size) { + let coords = getCoordsFromIndex(index); + let switchedIndex = getIndexFromCoords${this.outputShape.length}D(${e}(${t}), uniforms.reshapedPaddedXShape); + let paddedCoords = getPaddedXCoordsFromIndex(switchedIndex); + ${Pk(this.xShape,!0)} + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ice=n=>{const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{blockShape:i,paddings:o}=s;N(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGPU backend not implemented yet");const a=i.reduce((v,b)=>v*b),l=[[0,0]];l.push(...o);for(let v=1+i.length;vv[0]+r.shape[b]+v[1]),u=Dl(c,i,a,!1),h=Pl(u.length,i.length,!1),d=Ll(c,i,a,!1),p=it(c),f=new rce(r.shape,c,l,u,h,p.length),x=[{type:"int32",data:u},{type:"int32",data:p}];l.map(v=>x.push({type:"int32",data:[v[0],v[1]]}));const m=t.runWebGPUProgram(f,[r],r.dtype,x),g=tt({inputs:{x:m},backend:t,attrs:{shape:d}});return t.disposeData(m.dataId),g},oce={kernelName:jd,backendName:"webgpu",kernelFunc:ice};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ace{constructor(e,t,s){this.variableNames=["input","indices","segmentIds"],this.outputShape=[],this.uniforms="segmentSize : i32, sparseSize : i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=e,this.type=s,this.dispatchLayout=Xe([t]),this.dispatch=Le(this.dispatchLayout,[t],this.workgroupSize),this.shaderKey="sparseSegmentSum"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.sparseSize) { + let indexInSegmentIds = index / uniforms.segmentSize; + let indexInSegment = index % uniforms.segmentSize; + let indexInInput = indices[indexInSegmentIds]; + let segmentId = segmentIds[indexInSegmentIds]; + + let value = input[indexInInput * uniforms.segmentSize + indexInSegment]; + let outIndex = segmentId * uniforms.segmentSize + indexInSegment; + ${Aa("&result[outIndex]","value",this.type)} + } + } + `}}class lce{constructor(e,t){this.variableNames=["segmentIds"],this.outputShape=[],this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=[e],this.dispatchLayout=Xe(t),this.dispatch=Le(this.dispatchLayout,t,this.workgroupSize),this.shaderKey="sparseSegmentIdCountProgram"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.segmentIdsShape) { + let segmentId = segmentIds[index]; + ${Aa("&result[segmentId]","1","int32")} + } + } + `}}class cce{constructor(e,t){this.variableNames=["segmentSum","sameSegmentIdCount"],this.outputShape=[],this.uniforms="segmentSize : i32",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.type=t,this.dispatchLayout=Xe(e),this.dispatch=Le(this.dispatchLayout,e,this.workgroupSize),this.shaderKey="sparseSegmentMean"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let segmentId = index / uniforms.segmentSize; + let count = sameSegmentIdCount[segmentId]; + if (count != 0) { + ${this.type==="float32"?"setOutputAtIndex(index, segmentSum[index] / f32(count));":"setOutputAtIndexI32(index, segmentSum[index] / count);"} + } + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Lk(n,e,t,s=!1,r){const o=re(n.shape)/n.shape[0],a=n.dtype,l=re(e.shape),c=r.readSync(t.dataId),h=l>0?c[l-1]+1:0;let d;const p=n.shape.slice();p[0]=h;const f=l*o,x=sr({backend:r,attrs:{shape:p,value:0,dtype:a}});d=new ace(p,f,a);let m=[{type:"int32",data:[o]},{type:"int32",data:[f]}];const g=r.runWebGPUProgram(d,[n,e,t],a,m,x);if(s)return g;const v=sr({backend:r,attrs:{shape:[h],value:0,dtype:"int32"}});d=new lce(h,t.shape);const b=r.runWebGPUProgram(d,[t],"int32",null,v),y=sr({backend:r,attrs:{shape:p,value:0,dtype:a}});d=new cce(p,a),m=[{type:"int32",data:[o]}];const w=r.runWebGPUProgram(d,[g,b],a,m,y);return r.disposeData(g.dataId),r.disposeData(b.dataId),w}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function uce(n){const{inputs:e,backend:t}=n,{data:s,indices:r,segmentIds:i}=e;return Lk(s,r,i,!1,t)}const hce={kernelName:y2,backendName:"webgpu",kernelFunc:uce};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function dce(n){const{inputs:e,backend:t}=n,{data:s,indices:r,segmentIds:i}=e;return Lk(s,r,i,!0,t)}const pce={kernelName:w2,backendName:"webgpu",kernelFunc:dce};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class fce{constructor(e,t){this.variableNames=["A"],this.workgroupSize=[64,1,1],this.size=!0;const s=new Array(e.length);for(let r=0;r=5)throw Error(`Tile for rank ${n} is not yet supported`);if(n===1)return`(resRC % ${e}aShape)`;const t=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let r=0;r=5){const l=t.readSync(r.dataId),c=r.dtype==="string"?l.map(d=>Ci(d)):l,u=Tt(r.shape,r.dtype,c),h=rse(u,i);return t.makeTensorInfo(h.shape,h.dtype,h.values)}const o=new fce(r.shape,i);return t.runWebGPUProgram(o,[r],r.dtype)}const gce={kernelName:Wu,backendName:"webgpu",kernelFunc:ob};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xce(n){const{inputs:e,backend:t,attrs:s}=n,{sparseIndices:r,sparseValues:i,defaultValue:o}=e,{outputShape:a}=s,{sliceRank:l,numUpdates:c,sliceSize:u,strides:h,outputSize:d}=so(i,r,a),p=!1;if(i.dtype==="string"){const E=t.bufferSync(r),R=t.bufferSync(i),_=Ci(t.readSync(o.dataId)[0]),k=Jne(E,R,a,d,u,c,l,h,_,p);return t.makeTensorInfo(a,k.dtype,k.values)}const f=[d/u,u],x=tt({inputs:{x:r},backend:t,attrs:{shape:[c,l]}}),m=i.shape.length?tt({inputs:{x:i},backend:t,attrs:{shape:[c,u]}}):br({inputs:{x:i},backend:t}),g=m.dtype,v=t.makeTensorInfo([],g,Cs(1,g)),b=tt({inputs:{x:o},backend:t,attrs:{shape:Array(f.length).fill(1)}}),y=ob({inputs:{x:b},backend:t,attrs:{reps:f}}),w=re([c,u]),C=[{type:"int32",data:[l]},{type:"int32",data:h},{type:"int32",data:[w]}];switch(c){case 0:break;case 1:{const E=new $h([c,u],l,x.shape.length,m.shape.length,h,f,g,p);t.runWebGPUProgram(E,[m,x],g,C,y)}break;default:{const E=new $h([c,u],l,x.shape.length,v.shape.length,h,f,g,p);t.runWebGPUProgram(E,[v,x],g,C,y)}{const E=new $h([c,u],l,x.shape.length,m.shape.length,h,f,g);t.runWebGPUProgram(E,[m,x],g,C,y)}}const T=tt({inputs:{x:y},backend:t,attrs:{shape:a}});return t.disposeData(x.dataId),t.disposeData(m.dataId),t.disposeData(b.dataId),t.disposeData(v.dataId),t.disposeData(y.dataId),T}const vce={kernelName:S2,backendName:"webgpu",kernelFunc:xce};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bce(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{numOrSizeSplits:i,axis:o}=s,a=It(o,r.shape)[0],l=Pm(r,i,a),c=r.shape.length,u=new Array(c).fill(0),h=r.shape.slice();return l.map(d=>{const p=[...h];p[a]=d;const f=ih({inputs:{x:r},backend:t,attrs:{begin:u,size:p}});return u[a]+=d,f})}const yce={kernelName:Yd,backendName:"webgpu",kernelFunc:bce};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wce=jt({opType:Me.SQRT}),Sce={kernelName:Ou,backendName:"webgpu",kernelFunc:wce};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Cce={kernelName:Q0,backendName:"webgpu",kernelFunc:({inputs:n,backend:e})=>{const{x:t}=n,s=e,r=new rh(t.shape,Me.SQUARE);return s.runWebGPUProgram(r,[t],t.dtype)}};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _ce=xs({opType:bt.SQUARED_DIFFERENCE}),Tce={kernelName:zu,backendName:"webgpu",kernelFunc:_ce};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ice({inputs:n,attrs:e,backend:t}){const{x:s}=n,r=new rh(s.shape,Me.STEP,"stepAlpha : f32,"),i=[{type:"float32",data:[e.alpha]}];return t.runWebGPUProgram(r,[s],s.dtype,i)}const Ece={kernelName:Gu,backendName:"webgpu",kernelFunc:Ice};/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class kce{constructor(e){this.variableNames=["x"],this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]);const t=zn(this.outputShape.length);this.uniforms=`begin : ${t}, strides : ${t}, `,this.shaderKey="stridedSlice"}getUserCode(){const e=this.outputShape.length;let t="";if(e===1)t="coords * uniforms.strides + uniforms.begin";else{let r=0;t=this.outputShape.map((i,o)=>(r++,this.outputShape.length===1?`coords * uniforms.strides[${o}] + uniforms.begin[${o}]`:`coords[${r-1}] * uniforms.strides[${o}] + uniforms.begin[${o}]`)).join(",")}return` + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + setOutputAtIndex(index, getX(${t})); + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ace(n){const{inputs:e,backend:t,attrs:s}=n,{x:r}=e,{begin:i,end:o,strides:a,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:h,shrinkAxisMask:d}=s,{finalShapeSparse:p,finalShape:f,isIdentity:x,sliceDim0:m,isSimpleSlice:g,begin:v,end:b,strides:y}=pv(r.shape,i,o,a,l,c,u,h,d);let w;if(x)w=tt({inputs:{x:r},backend:t,attrs:{shape:f}});else if(m||g){N(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);const C=dv(v,b,y),T=ih({inputs:{x:r},backend:t,attrs:{begin:v,size:C}});w=tt({inputs:{x:T},backend:t,attrs:{shape:f}}),t.disposeData(T.dataId)}else if(t.shouldExecuteOnCPU([r])){const T=t.readSync(r.dataId),E=Tt(r.shape,r.dtype,T),R=tse(p,E,y,v);w=t.makeTensorInfo(f,r.dtype,R.values)}else{const T=new kce(p),E=[{type:"int32",data:v},{type:"int32",data:y}],R=t.runWebGPUProgram(T,[r],r.dtype,E);w=tt({inputs:{x:R},backend:t,attrs:{shape:f}}),t.disposeData(R.dataId)}return w}const Rce={kernelName:em,backendName:"webgpu",kernelFunc:Ace};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Mce(n){const{inputs:e,backend:t,attrs:s}=n,{separator:r,nGramWidths:i,leftPad:o,rightPad:a,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:h}=e,d=t.readSync(u.dataId),p=t.readSync(h.dataId),[f,x]=nse(d,p,r,i,o,a,l,c);return[t.makeTensorInfo([f.length],"string",f),t.makeTensorInfo(h.shape,"int32",x)]}const Nce={kernelName:_2,backendName:"webgpu",kernelFunc:Mce};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $ce=xs({opType:bt.SUB,cpuKernelImpl:sse,supportsComplex:!0}),Dce={kernelName:Bu,backendName:"webgpu",kernelFunc:$ce};/** + * @license + * Copyright 2022 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Pce=jt({opType:Me.TAN}),Lce={kernelName:Uu,backendName:"webgpu",kernelFunc:Pce};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Fce=jt({opType:Me.TANH}),Oce={kernelName:Vu,backendName:"webgpu",kernelFunc:Fce};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function zce(n){const{inputs:e,backend:t,attrs:s}=n,{tensor:r,indices:i,updates:o}=e,{sliceRank:a,numUpdates:l,sliceSize:c,strides:u,outputSize:h}=so(o,i,r.shape),d=[h/c,c];if(h===0)return t.makeTensorInfo(r.shape,i.dtype);const p=[],f=tt({inputs:{x:i},backend:t,attrs:{shape:[l,a]}});p.push(f);const x=tt({inputs:{x:o},backend:t,attrs:{shape:[l,c]}});p.push(x);const m=tt({inputs:{x:r},backend:t,attrs:{shape:d}});p.push(m);const g=ob({inputs:{x:m},backend:t,attrs:{reps:Array(d.length).fill(1)}}),v=new $h([l,c],a,f.shape.length,x.shape.length,u,d,r.dtype,!1),b=re([l,c]),y=[{type:"int32",data:[a]},{type:"int32",data:u},{type:"int32",data:[b]}],w=t.runWebGPUProgram(v,[x,f],m.dtype,y,g);p.push(w);const C=tt({inputs:{x:w},backend:t,attrs:{shape:r.shape}});return p.forEach(T=>t.disposeData(T.dataId)),C}const Bce={kernelName:v2,backendName:"webgpu",kernelFunc:zce};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Uce{constructor(e){this.variableNames=["x","indices"],this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms=`inputSize : i32, firstPass : i32, negativeInf : f32, + dir : i32, inc : i32,`,this.shaderKey="swap"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let outC = getCoordsFromIndex(index); + let batch = outC[0]; + let elemIdx = outC[1]; + // We compare elements pair-wise within a group of size 2 * inc. + // The comparing rule for each group alternates between ascending + // and descending. Within each group, we compare each pair at + // positions i and i+inc. To decide whether an element at position i + // is x0 or x1, we mod it by 2 * inc, if the result is smaller than + // inc, it is in the first half of the group, we denote it as x0, + // otherwise we denote it as x1. + // For example, as shown in the Bitonic top K paper referenced + // above, Figure5(a) shows that element[1] is in the second half of + // the group when group size is 2, but it is in the first half of + // the group when group size is 4. + let isFirstInPair = elemIdx % (2 * uniforms.inc) < uniforms.inc; + var i = 0; + if (isFirstInPair) { + i = elemIdx; + } else { + i = elemIdx - uniforms.inc; + } + + var i0 = 0; + if (uniforms.firstPass == 1) { + i0 = i; + } else { + i0 = i32(getIndices(batch, i)); + } + + var i1 = 0; + if (uniforms.firstPass == 1) { + i1 = i + uniforms.inc; + } else { + i1 = i32(getIndices(batch, i + uniforms.inc)); + } + + var x0 = f32(0.0); + var x1 = f32(0.0); + if (i0 < uniforms.inputSize) { + x0 = getX(batch, i0); + } else { + x0 = uniforms.negativeInf; + } + if (i1 < uniforms.inputSize) { + x1 = getX(batch, i1); + } else { + x1 = uniforms.negativeInf; + } + + let reverse = elemIdx % (2 * uniforms.dir) >= uniforms.dir; + let isGreater = x0 > x1 || (x0 == x1 && i1 > i0); + if (reverse == isGreater) { + // Elements in opposite order of direction + let iTemp = i0; + i0 = i1; + i1 = iTemp; + } + if (isFirstInPair) { + setOutputAtIndex(index, f32(i0)); + } else { + setOutputAtIndex(index, f32(i1)); + } + } + } + `}}class Vce{constructor(e){this.variableNames=["x","indices"],this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms="inputSize : i32, firstPass : i32, k : i32,",this.shaderKey="merge"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.size) { + let outC = getCoordsFromIndex(index); + let batch = outC[0]; + let elemIdx = outC[1]; + // The output size is half of the previous size. + // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ + // (k=4), we only need to output the indices at positions |, the + // indices at positions _ can be thrown away, see Figure5(b) After + // Phase 2 (Merge phase) in the Bitonic Top K paper referenced + // above. + // For example, the paper shows we only need to output the orange + // bars. The output sequence should look like this | | | | | | | |. + // Because the sequence is halved, to map the output index back to + // the previous sequence to find the corresponding value, we need + // to double the index. When we double the index, we basically + // interpolate a position, so 2i looks like + // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k + // position of each 2k positions by - elemIdx % k. E.g. for output + // at index 4,5,6,7, we want to get the corresponding element at + // original index 8,9,10,11, for output at index 8,9,10,11, + // we want to get the corresponding element at original index + // 16,17,18,19, so on and so forth. + + var i = 0; + if (elemIdx < uniforms.k) { + i = elemIdx; + } else { + i = elemIdx * 2 - elemIdx % uniforms.k; + } + var i0 = 0; + if (uniforms.firstPass == 1) { + i0 = i; + } else { + i0 = i32(getIndices(batch, i)); + } + var i1 = 0; + if (uniforms.firstPass == 1) { + i1 = i + uniforms.k; + } else { + i1 = i32(getIndices(batch, i + uniforms.k)); + } + + let x0 = getX(batch, i0); + var x1 = f32(0.0); + if (i1 < uniforms.inputSize) { + x1 = getX(batch, i1); + } else { + x1 = x0; + } + + if (x0 >= x1) { + setOutputAtIndex(index, f32(i0)); + } else { + setOutputAtIndex(index, f32(i1)); + } + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Yl(n,e){e!==null&&n.disposeData(e.dataId)}function Ow(n){let e=1;for(;ef===null?[h,h]:[h,f],m=(w,C,T)=>{const E=x(),R=new Uce(T),k=[{type:"int32",data:[l]},{type:"int32",data:[f===null?1:0]},{type:"float32",data:[Number.NEGATIVE_INFINITY]},{type:"int32",data:[w]},{type:"int32",data:[C]}],F=f;f=t.runWebGPUProgram(R,E,"int32",k),Yl(t,F)};for(let w=1;w=1;T/=2)m(C,T,[u,p])}for(let w=p;w>d;w/=2){const C=x(),T=new Vce([u,w/2]),R=[{type:"int32",data:[l]},{type:"int32",data:[f===null?1:0]},{type:"int32",data:[d]}],_=f;f=t.runWebGPUProgram(T,C,"int32",R),Yl(t,_);const k=d/2,F=k*2;for(let B=k;B>=1;B/=2)m(F,B,f.shape)}let g=f;f=ih({inputs:{x:f},backend:t,attrs:{begin:0,size:[u,i]}}),Yl(t,g);let v=Mk({inputs:{x:h,indices:f},backend:t,attrs:{axis:1,batchDims:1}});Yl(t,h);const b=a.slice(0,-1);b.push(i),g=f,f=tt({inputs:{x:f},attrs:{shape:b},backend:t}),Yl(t,g);const y=v;return v=tt({inputs:{x:v},attrs:{shape:b},backend:t}),Yl(t,y),[v,f]}const Gce={kernelName:tm,backendName:"webgpu",kernelFunc:Wce};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Hce{constructor(e){this.variableNames=["Image","Transforms"],this.uniforms="interpolationModeId : i32, fillModeId : i32, fillValue : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="transform"}getUserCode(){return` + fn mapCoord(outCoord : f32, len : f32) -> f32{ + var inCoord = outCoord; + if(uniforms.fillModeId == 2) { + if (inCoord < 0.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + let sz2 = 2.0 * len; + if (inCoord < sz2) { + inCoord = sz2 * f32(i32(f32(-inCoord / sz2))) + + inCoord; + } + if (inCoord < -len) { + inCoord = inCoord + sz2; + } else { + inCoord = -inCoord - 1.0; + } + } + } else if (inCoord > len - 1.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + let sz2 = 2.0 * len; + inCoord = inCoord - sz2 * f32(i32(f32(inCoord / sz2))); + if (inCoord >= len) { + inCoord = sz2 - inCoord - 1.0; + } + } + } + return clamp(inCoord, 0.0, len - 1.0); + } else if (uniforms.fillModeId == 3) { + if (inCoord < 0.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + let sz = len - 1.0; + inCoord = inCoord + len * (f32(i32(f32(-inCoord / sz))) + 1.0); + } + } else if (inCoord > len - 1.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + let sz = len - 1.0; + inCoord = inCoord - len * f32(i32(f32(inCoord / sz))); + } + } + return clamp(inCoord, 0.0, len - 1.0); + } else if (uniforms.fillModeId == 4) { + return clamp(outCoord, 0.0, len - 1.0); + } + return outCoord; + } + fn readWithFillValue(batch : i32, coordY : i32, coordX : i32, + channel : i32) -> f32 { + var outputValue : f32; + if (0 <= coordY && coordY < uniforms.imageShape[1] && 0 <= coordX && coordX < uniforms.imageShape[2]) { + outputValue = getImage(batch, coordY, coordX, channel); + } else { + outputValue = uniforms.fillValue; + } + return outputValue; + } + + ${De("index")} { + if (index < uniforms.size) { + let coords = getCoordsFromIndex(index); + var outputValue : f32; + let batch = coords[0]; + let x = coords[2]; + let y = coords[1]; + let channel = coords[3]; + let xf = f32(x); + let yf = f32(y); + let a1 = getTransforms(batch, 0); + let a2 = getTransforms(batch, 1); + let a3 = getTransforms(batch, 2); + let b1 = getTransforms(batch, 3); + let b2 = getTransforms(batch, 4); + let b3 = getTransforms(batch, 5); + let c1 = getTransforms(batch, 6); + let c2 = getTransforms(batch, 7); + let projection = c1 * xf + c2 * yf + 1.0; + if (projection == 0.0) { + outputValue = uniforms.fillValue; + } else { + let inX = (a1 * xf + a2 * yf + a3) / projection; + let inY = (b1 * xf + b2 * yf + b3) / projection; + let mapX = mapCoord(inX, f32(uniforms.imageShape[2])); + let mapY = mapCoord(inY, f32(uniforms.imageShape[1])); + + if (uniforms.interpolationModeId == 1) { + let coordY = i32(round(mapY)); + let coordX = i32(round(mapX)); + outputValue = readWithFillValue(batch, coordY, coordX, + channel); + } else { + let yFloor = floor(mapY); + let xFloor = floor(mapX); + let yCeil = yFloor + 1.0; + let xCeil = xFloor + 1.0; + let valueYFloor = (xCeil - mapX) * + readWithFillValue(batch, i32(yFloor), i32(xFloor), channel) + + (mapX - xFloor) * + readWithFillValue(batch, i32(yFloor), i32(xCeil), channel); + let valueYCeil = (xCeil - mapX) * + readWithFillValue(batch, i32(yCeil), i32(xFloor), channel) + + (mapX - xFloor) * + readWithFillValue(batch, i32(yCeil), i32(xCeil), channel); + outputValue = (yCeil - mapY) * valueYFloor + + (mapY - yFloor) * valueYCeil; + } + } + setOutputAtIndex(index, outputValue); + } + } + `}}/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qce(n){const{inputs:e,backend:t,attrs:s}=n,{image:r,transforms:i}=e,{interpolation:o,fillMode:a,fillValue:l,outputShape:c}=s,[u,h,d,p]=r.shape,[f,x]=c??[h,d],m=[u,f,x,p],g=new Hce(m),v=o==="nearest"?1:2;let b;switch(a){case"constant":b=1;break;case"reflect":b=2;break;case"wrap":b=3;break;case"nearest":b=4;break;default:b=1;break}const y=[{type:"int32",data:[v]},{type:"int32",data:[b]},{type:"float32",data:[l]}];return t.runWebGPUProgram(g,[r,i],"float32",y)}const Xce={kernelName:nm,backendName:"webgpu",kernelFunc:qce};/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Kce(n){const{inputs:e,backend:t,attrs:s}=n,{value:r}=e;let{axis:i}=s;i<0&&(i+=r.shape.length);const o=r,a=o.shape.length,l=r.shape[i],c=new Array(a-1);let u=0;for(let x=0;xt.disposeData(x.dataId)),f}const jce={kernelName:Jd,backendName:"webgpu",kernelFunc:Kce};/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Yce{constructor(e,t,s){if(this.outputShape=[],this.variableNames=["x","segmentIds"],this.uniforms="numSegments : i32, xSize: i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=t,this.dispatchLayout=Xe(e),this.dispatch=Le(this.dispatchLayout,e,this.workgroupSize),s!=="float32"&&s!=="int32")throw new Error(`UnsortedSegmentSum only supports float32 and int32 + types, does not support ${s} type.`);this.type=s,this.shaderKey="unsortedSegmentSum"}getUserCode(){return` + ${De("index")} { + if (index < uniforms.xSize) { + let coords = getXCoordsFromIndex(index); + let b = coords[0]; + let inCol = coords[1]; + + let segmentId = i32(getSegmentIds(inCol)); + if (segmentId >= 0) { + let flatIndex = b * uniforms.numSegments + segmentId % uniforms.numSegments; + let value = getX(b, inCol); + + ${Aa("&result[flatIndex]","value",this.type)} + } + } + } + `}}/** + * @license + * Copyright 2023 Google LLC. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Zce(n){const{inputs:e,backend:t,attrs:s}=n,{x:r,segmentIds:i}=e,{numSegments:o}=s,a=r.shape.length,l=[];let c=0;const u=ln([c],a);let h=r;u!=null&&(h=to({inputs:{x:r},backend:t,attrs:{perm:u}}),l.push(h),c=xn(1,a)[0]);const d=W4(h.shape,c,o),p=re([h.shape[c]]),f=tt({inputs:{x:h},backend:t,attrs:{shape:[-1,p]}});l.push(f);const x=r.dtype,m=[f.shape[0],o],g=sr({backend:t,attrs:{shape:m,value:0,dtype:x}}),v=new Yce(f.shape,m,x),b=[{type:"int32",data:[o]},{type:"int32",data:[re(f.shape)]}],y=t.runWebGPUProgram(v,[f,i],x,b,g),w=tt({inputs:{x:y},backend:t,attrs:{shape:d}});l.push(y);let C=w;if(u!=null){l.push(w);const T=no(u);C=to({inputs:{x:C},backend:t,attrs:{perm:T}})}return l.forEach(T=>t.disposeData(T.dataId)),C}const Jce={kernelName:Qd,backendName:"webgpu",kernelFunc:Zce};/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qce=[_ne,lse,use,dse,fse,xse,_se,Ise,kse,Rse,Nse,Dse,Lse,Ose,Bse,Hse,Xse,Zse,Qse,tre,ore,ure,pre,xre,bre,Cre,Ine,Ire,Rre,Ore,Gre,Kre,Zre,Qre,tie,sie,iie,lie,uie,die,fie,xie,_ie,Iie,yie,Aie,Nie,Lie,Oie,Uie,Hie,Xie,jie,Zie,Qie,toe,noe,roe,ooe,wne,loe,foe,uoe,doe,xoe,boe,woe,_oe,Eoe,Aoe,Moe,Tne,$oe,kre,Poe,Foe,zoe,Uoe,Woe,Hoe,Koe,Joe,Yoe,eae,nae,rae,lae,hae,Vse,pae,mae,Cae,xae,wae,Tae,Wse,Eae,Aae,Mae,$ae,Oae,Vie,Bae,Vae,Gae,fre,Xae,jae,Zae,ele,nle,rle,ole,lle,mre,ule,dle,fle,gle,Sne,ble,Sle,Tle,kle,Mle,$le,Ple,Fle,zle,Vle,Hle,Xle,jle,Zle,Qle,tce,rre,Ece,Rce,Nce,Lae,sce,oce,hce,pce,vce,yce,Sce,Cce,Tce,Dce,Wie,Lce,Oce,Bce,gce,Gce,Xce,yse,jce,Jce,Kae];for(const n of Qce)E2(n);const kn={width:800,height:400,floorY:320,deathY:400};function eue(n){let e=n|0||1;return()=>(e^=e<<13,e^=e>>>17,e^=e<<5,(e>>>0)/4294967295)}function tue(n){const e=eue(n),t=[];t.push({x:0,y:kn.floorY,width:120});let s=120;const r=40,i=90,o=80,a=160;for(;s=kn.width-140)break;const u=o+e()*(a-o),h=(e()-.5)*40;t.push({x:s,y:kn.floorY+h,width:u}),s+=u}const l=120;return t.push({x:kn.width-l,y:kn.floorY,width:l}),{platforms:t,goalX:kn.width-40,deathY:kn.deathY}}const nue=24,Rx=["noop","left","right","jump"],sue=.6,zw=.8,Hg=4,rue=.8,iue=-10,Bw=16,Gp=20;class oue{level;x=0;y=0;vx=0;vy=0;onGround=!1;prevX=0;steps=0;maxSteps=1500;reset(e){return this.level=tue(e),this.x=20,this.y=kn.floorY-Gp,this.vx=0,this.vy=0,this.onGround=!1,this.prevX=this.x,this.steps=0,this.obs()}forceState(e){this.x=e.x,this.y=e.y,this.vx=e.vx,this.vy=e.vy,this.onGround=!1,this.prevX=e.x}step(e){this.prevX=this.x,this.steps+=1,e===1?this.vx=Math.max(-Hg,this.vx-zw):e===2?this.vx=Math.min(Hg,this.vx+zw):e===3&&this.onGround?(this.vy=iue,this.onGround=!1):e===0&&this.onGround&&(this.vx*=rue),this.vy+=sue,this.x+=this.vx,this.y+=this.vy,this.onGround=!1;for(const i of this.level.platforms)if(this.x+Bw>i.x&&this.xo&&this.y+Gp-this.vy<=o+1&&(this.y=o-Gp,this.vy=0,this.onGround=!0)}let t=0;const s=this.x-this.prevX;s>0&&(t+=.01*s);let r=!1;return this.y>this.level.deathY?(t+=-1,r=!0):this.x+Bw/2>=this.level.goalX?(t+=1,r=!0):this.steps>=this.maxSteps&&(t+=-.2,r=!0),{obs:this.obs(),reward:t,done:r}}obs(){const e=new Float32Array(nue);e[0]=this.x/kn.width,e[1]=this.y/kn.height,e[2]=this.vx/Hg,e[3]=this.vy/20;const t=this.level.platforms.filter(i=>i.x+i.width>this.x).sort((i,o)=>i.x-o.x).slice(0,4);for(let i=0;i<4;i++){const o=t[i],a=4+i*3;o&&(e[a+0]=(o.x-this.x)/kn.width,e[a+1]=o.y/kn.height,e[a+2]=o.width/kn.width)}const s=[...this.level.platforms].sort((i,o)=>i.x-o.x),r=[];for(let i=1;i0&&o>=this.x-10&&r.push({x:o,w:a}),r.length>=4)break}for(let i=0;i<4;i++){const o=r[i],a=16+i*2;o&&(e[a+0]=(o.x-this.x)/kn.width,e[a+1]=o.w/kn.width)}return e}}/** + * @license + * Copyright 2010-2023 Three.js Authors + * SPDX-License-Identifier: MIT + */const ab="161",aue=0,Uw=1,lue=2,Fk=1,cue=2,go=3,pa=0,mr=1,Bi=2,sa=0,_c=1,Vw=2,Ww=3,Gw=4,uue=5,Za=100,hue=101,due=102,Hw=103,qw=104,pue=200,fue=201,mue=202,gue=203,Mx=204,Nx=205,xue=206,vue=207,bue=208,yue=209,wue=210,Sue=211,Cue=212,_ue=213,Tue=214,Iue=0,Eue=1,kue=2,a0=3,Aue=4,Rue=5,Mue=6,Nue=7,Ok=0,$ue=1,Due=2,ra=0,Pue=1,Lue=2,Fue=3,Oue=4,zue=5,Bue=6,zk=300,Uc=301,Vc=302,$x=303,Dx=304,rg=306,Px=1e3,fi=1001,Lx=1002,Xs=1003,Xw=1004,xh=1005,ur=1006,qg=1007,sl=1008,ia=1009,Uue=1010,Vue=1011,lb=1012,Bk=1013,Zo=1014,yo=1015,Jh=1016,Uk=1017,Vk=1018,cl=1020,Wue=1021,mi=1023,Gue=1024,Hue=1025,ul=1026,Wc=1027,que=1028,Wk=1029,Xue=1030,Gk=1031,Hk=1033,Xg=33776,Kg=33777,jg=33778,Yg=33779,Kw=35840,jw=35841,Yw=35842,Zw=35843,qk=36196,Jw=37492,Qw=37496,e3=37808,t3=37809,n3=37810,s3=37811,r3=37812,i3=37813,o3=37814,a3=37815,l3=37816,c3=37817,u3=37818,h3=37819,d3=37820,p3=37821,Zg=36492,f3=36494,m3=36495,Kue=36283,g3=36284,x3=36285,v3=36286,Xk=3e3,hl=3001,jue=3200,Yue=3201,Zue=0,Jue=1,qr="",Is="srgb",Ro="srgb-linear",cb="display-p3",ig="display-p3-linear",l0="linear",Tn="srgb",c0="rec709",u0="p3",Zl=7680,b3=519,Que=512,ehe=513,the=514,Kk=515,nhe=516,she=517,rhe=518,ihe=519,y3=35044,w3="300 es",Fx=1035,Co=2e3,h0=2001;class oh{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(t)===-1&&s[e].push(t)}hasEventListener(e,t){if(this._listeners===void 0)return!1;const s=this._listeners;return s[e]!==void 0&&s[e].indexOf(t)!==-1}removeEventListener(e,t){if(this._listeners===void 0)return;const r=this._listeners[e];if(r!==void 0){const i=r.indexOf(t);i!==-1&&r.splice(i,1)}}dispatchEvent(e){if(this._listeners===void 0)return;const s=this._listeners[e.type];if(s!==void 0){e.target=this;const r=s.slice(0);for(let i=0,o=r.length;i>8&255]+Ds[n>>16&255]+Ds[n>>24&255]+"-"+Ds[e&255]+Ds[e>>8&255]+"-"+Ds[e>>16&15|64]+Ds[e>>24&255]+"-"+Ds[t&63|128]+Ds[t>>8&255]+"-"+Ds[t>>16&255]+Ds[t>>24&255]+Ds[s&255]+Ds[s>>8&255]+Ds[s>>16&255]+Ds[s>>24&255]).toLowerCase()}function dr(n,e,t){return Math.max(e,Math.min(t,n))}function ohe(n,e){return(n%e+e)%e}function Qg(n,e,t){return(1-t)*n+t*e}function S3(n){return(n&n-1)===0&&n!==0}function zx(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function vh(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function cr(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}class en{constructor(e=0,t=0){en.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,s=this.y,r=e.elements;return this.x=r[0]*t+r[3]*s+r[6],this.y=r[1]*t+r[4]*s+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(e,Math.min(t,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(dr(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y;return t*t+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const s=Math.cos(t),r=Math.sin(t),i=this.x-e.x,o=this.y-e.y;return this.x=i*s-o*r+e.x,this.y=i*r+o*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Vt{constructor(e,t,s,r,i,o,a,l,c){Vt.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,s,r,i,o,a,l,c)}set(e,t,s,r,i,o,a,l,c){const u=this.elements;return u[0]=e,u[1]=r,u[2]=a,u[3]=t,u[4]=i,u[5]=l,u[6]=s,u[7]=o,u[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],this}extractBasis(e,t,s){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),s.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,r=t.elements,i=this.elements,o=s[0],a=s[3],l=s[6],c=s[1],u=s[4],h=s[7],d=s[2],p=s[5],f=s[8],x=r[0],m=r[3],g=r[6],v=r[1],b=r[4],y=r[7],w=r[2],C=r[5],T=r[8];return i[0]=o*x+a*v+l*w,i[3]=o*m+a*b+l*C,i[6]=o*g+a*y+l*T,i[1]=c*x+u*v+h*w,i[4]=c*m+u*b+h*C,i[7]=c*g+u*y+h*T,i[2]=d*x+p*v+f*w,i[5]=d*m+p*b+f*C,i[8]=d*g+p*y+f*T,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[1],r=e[2],i=e[3],o=e[4],a=e[5],l=e[6],c=e[7],u=e[8];return t*o*u-t*a*c-s*i*u+s*a*l+r*i*c-r*o*l}invert(){const e=this.elements,t=e[0],s=e[1],r=e[2],i=e[3],o=e[4],a=e[5],l=e[6],c=e[7],u=e[8],h=u*o-a*c,d=a*l-u*i,p=c*i-o*l,f=t*h+s*d+r*p;if(f===0)return this.set(0,0,0,0,0,0,0,0,0);const x=1/f;return e[0]=h*x,e[1]=(r*c-u*s)*x,e[2]=(a*s-r*o)*x,e[3]=d*x,e[4]=(u*t-r*l)*x,e[5]=(r*i-a*t)*x,e[6]=p*x,e[7]=(s*l-c*t)*x,e[8]=(o*t-s*i)*x,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,s,r,i,o,a){const l=Math.cos(i),c=Math.sin(i);return this.set(s*l,s*c,-s*(l*o+c*a)+o+e,-r*c,r*l,-r*(-c*o+l*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(e1.makeScale(e,t)),this}rotate(e){return this.premultiply(e1.makeRotation(-e)),this}translate(e,t){return this.premultiply(e1.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,s,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,s=e.elements;for(let r=0;r<9;r++)if(t[r]!==s[r])return!1;return!0}fromArray(e,t=0){for(let s=0;s<9;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const e1=new Vt;function jk(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}function d0(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function ahe(){const n=d0("canvas");return n.style.display="block",n}const C3={};function Tc(n){n in C3||(C3[n]=!0,console.warn(n))}const _3=new Vt().set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),T3=new Vt().set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),Hp={[Ro]:{transfer:l0,primaries:c0,toReference:n=>n,fromReference:n=>n},[Is]:{transfer:Tn,primaries:c0,toReference:n=>n.convertSRGBToLinear(),fromReference:n=>n.convertLinearToSRGB()},[ig]:{transfer:l0,primaries:u0,toReference:n=>n.applyMatrix3(T3),fromReference:n=>n.applyMatrix3(_3)},[cb]:{transfer:Tn,primaries:u0,toReference:n=>n.convertSRGBToLinear().applyMatrix3(T3),fromReference:n=>n.applyMatrix3(_3).convertLinearToSRGB()}},lhe=new Set([Ro,ig]),cn={enabled:!0,_workingColorSpace:Ro,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(n){if(!lhe.has(n))throw new Error(`Unsupported working color space, "${n}".`);this._workingColorSpace=n},convert:function(n,e,t){if(this.enabled===!1||e===t||!e||!t)return n;const s=Hp[e].toReference,r=Hp[t].fromReference;return r(s(n))},fromWorkingColorSpace:function(n,e){return this.convert(n,this._workingColorSpace,e)},toWorkingColorSpace:function(n,e){return this.convert(n,e,this._workingColorSpace)},getPrimaries:function(n){return Hp[n].primaries},getTransfer:function(n){return n===qr?l0:Hp[n].transfer}};function Ic(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function t1(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}let Jl;class Yk{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{Jl===void 0&&(Jl=d0("canvas")),Jl.width=e.width,Jl.height=e.height;const s=Jl.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),t=Jl}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=d0("canvas");t.width=e.width,t.height=e.height;const s=t.getContext("2d");s.drawImage(e,0,0,e.width,e.height);const r=s.getImageData(0,0,e.width,e.height),i=r.data;for(let o=0;o0&&(s.userData=this.userData),t||(e.textures[this.uuid]=s),s}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==zk)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Px:e.x=e.x-Math.floor(e.x);break;case fi:e.x=e.x<0?0:1;break;case Lx:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Px:e.y=e.y-Math.floor(e.y);break;case fi:e.y=e.y<0?0:1;break;case Lx:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}get encoding(){return Tc("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===Is?hl:Xk}set encoding(e){Tc("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=e===hl?Is:qr}}gr.DEFAULT_IMAGE=null;gr.DEFAULT_MAPPING=zk;gr.DEFAULT_ANISOTROPY=1;class Es{constructor(e=0,t=0,s=0,r=1){Es.prototype.isVector4=!0,this.x=e,this.y=t,this.z=s,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,s,r){return this.x=e,this.y=t,this.z=s,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,s=this.y,r=this.z,i=this.w,o=e.elements;return this.x=o[0]*t+o[4]*s+o[8]*r+o[12]*i,this.y=o[1]*t+o[5]*s+o[9]*r+o[13]*i,this.z=o[2]*t+o[6]*s+o[10]*r+o[14]*i,this.w=o[3]*t+o[7]*s+o[11]*r+o[15]*i,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,s,r,i;const l=e.elements,c=l[0],u=l[4],h=l[8],d=l[1],p=l[5],f=l[9],x=l[2],m=l[6],g=l[10];if(Math.abs(u-d)<.01&&Math.abs(h-x)<.01&&Math.abs(f-m)<.01){if(Math.abs(u+d)<.1&&Math.abs(h+x)<.1&&Math.abs(f+m)<.1&&Math.abs(c+p+g-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const b=(c+1)/2,y=(p+1)/2,w=(g+1)/2,C=(u+d)/4,T=(h+x)/4,E=(f+m)/4;return b>y&&b>w?b<.01?(s=0,r=.707106781,i=.707106781):(s=Math.sqrt(b),r=C/s,i=T/s):y>w?y<.01?(s=.707106781,r=0,i=.707106781):(r=Math.sqrt(y),s=C/r,i=E/r):w<.01?(s=.707106781,r=.707106781,i=0):(i=Math.sqrt(w),s=T/i,r=E/i),this.set(s,r,i,t),this}let v=Math.sqrt((m-f)*(m-f)+(h-x)*(h-x)+(d-u)*(d-u));return Math.abs(v)<.001&&(v=1),this.x=(m-f)/v,this.y=(h-x)/v,this.z=(d-u)/v,this.w=Math.acos((c+p+g-1)/2),this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this.w=Math.max(e.w,Math.min(t.w,this.w)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this.w=Math.max(e,Math.min(t,this.w)),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(e,Math.min(t,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this.w=e.w+(t.w-e.w)*s,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class hhe extends oh{constructor(e=1,t=1,s={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new Es(0,0,e,t),this.scissorTest=!1,this.viewport=new Es(0,0,e,t);const r={width:e,height:t,depth:1};s.encoding!==void 0&&(Tc("THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace."),s.colorSpace=s.encoding===hl?Is:qr),s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:ur,depthBuffer:!0,stencilBuffer:!1,depthTexture:null,samples:0},s),this.texture=new gr(r,s.mapping,s.wrapS,s.wrapT,s.magFilter,s.minFilter,s.format,s.type,s.anisotropy,s.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.flipY=!1,this.texture.generateMipmaps=s.generateMipmaps,this.texture.internalFormat=s.internalFormat,this.depthBuffer=s.depthBuffer,this.stencilBuffer=s.stencilBuffer,this.depthTexture=s.depthTexture,this.samples=s.samples}setSize(e,t,s=1){(this.width!==e||this.height!==t||this.depth!==s)&&(this.width=e,this.height=t,this.depth=s,this.texture.image.width=e,this.texture.image.height=t,this.texture.image.depth=s,this.dispose()),this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.texture=e.texture.clone(),this.texture.isRenderTargetTexture=!0;const t=Object.assign({},e.texture.image);return this.texture.source=new Zk(t),this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Tl extends hhe{constructor(e=1,t=1,s={}){super(e,t,s),this.isWebGLRenderTarget=!0}}class Jk extends gr{constructor(e=null,t=1,s=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:s,depth:r},this.magFilter=Xs,this.minFilter=Xs,this.wrapR=fi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class dhe extends gr{constructor(e=null,t=1,s=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:s,depth:r},this.magFilter=Xs,this.minFilter=Xs,this.wrapR=fi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Cp{constructor(e=0,t=0,s=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=s,this._w=r}static slerpFlat(e,t,s,r,i,o,a){let l=s[r+0],c=s[r+1],u=s[r+2],h=s[r+3];const d=i[o+0],p=i[o+1],f=i[o+2],x=i[o+3];if(a===0){e[t+0]=l,e[t+1]=c,e[t+2]=u,e[t+3]=h;return}if(a===1){e[t+0]=d,e[t+1]=p,e[t+2]=f,e[t+3]=x;return}if(h!==x||l!==d||c!==p||u!==f){let m=1-a;const g=l*d+c*p+u*f+h*x,v=g>=0?1:-1,b=1-g*g;if(b>Number.EPSILON){const w=Math.sqrt(b),C=Math.atan2(w,g*v);m=Math.sin(m*C)/w,a=Math.sin(a*C)/w}const y=a*v;if(l=l*m+d*y,c=c*m+p*y,u=u*m+f*y,h=h*m+x*y,m===1-a){const w=1/Math.sqrt(l*l+c*c+u*u+h*h);l*=w,c*=w,u*=w,h*=w}}e[t]=l,e[t+1]=c,e[t+2]=u,e[t+3]=h}static multiplyQuaternionsFlat(e,t,s,r,i,o){const a=s[r],l=s[r+1],c=s[r+2],u=s[r+3],h=i[o],d=i[o+1],p=i[o+2],f=i[o+3];return e[t]=a*f+u*h+l*p-c*d,e[t+1]=l*f+u*d+c*h-a*p,e[t+2]=c*f+u*p+a*d-l*h,e[t+3]=u*f-a*h-l*d-c*p,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,s,r){return this._x=e,this._y=t,this._z=s,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const s=e._x,r=e._y,i=e._z,o=e._order,a=Math.cos,l=Math.sin,c=a(s/2),u=a(r/2),h=a(i/2),d=l(s/2),p=l(r/2),f=l(i/2);switch(o){case"XYZ":this._x=d*u*h+c*p*f,this._y=c*p*h-d*u*f,this._z=c*u*f+d*p*h,this._w=c*u*h-d*p*f;break;case"YXZ":this._x=d*u*h+c*p*f,this._y=c*p*h-d*u*f,this._z=c*u*f-d*p*h,this._w=c*u*h+d*p*f;break;case"ZXY":this._x=d*u*h-c*p*f,this._y=c*p*h+d*u*f,this._z=c*u*f+d*p*h,this._w=c*u*h-d*p*f;break;case"ZYX":this._x=d*u*h-c*p*f,this._y=c*p*h+d*u*f,this._z=c*u*f-d*p*h,this._w=c*u*h+d*p*f;break;case"YZX":this._x=d*u*h+c*p*f,this._y=c*p*h+d*u*f,this._z=c*u*f-d*p*h,this._w=c*u*h-d*p*f;break;case"XZY":this._x=d*u*h-c*p*f,this._y=c*p*h-d*u*f,this._z=c*u*f+d*p*h,this._w=c*u*h+d*p*f;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const s=t/2,r=Math.sin(s);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,s=t[0],r=t[4],i=t[8],o=t[1],a=t[5],l=t[9],c=t[2],u=t[6],h=t[10],d=s+a+h;if(d>0){const p=.5/Math.sqrt(d+1);this._w=.25/p,this._x=(u-l)*p,this._y=(i-c)*p,this._z=(o-r)*p}else if(s>a&&s>h){const p=2*Math.sqrt(1+s-a-h);this._w=(u-l)/p,this._x=.25*p,this._y=(r+o)/p,this._z=(i+c)/p}else if(a>h){const p=2*Math.sqrt(1+a-s-h);this._w=(i-c)/p,this._x=(r+o)/p,this._y=.25*p,this._z=(l+u)/p}else{const p=2*Math.sqrt(1+h-s-a);this._w=(o-r)/p,this._x=(i+c)/p,this._y=(l+u)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return sMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=s):(this._x=0,this._y=-e.z,this._z=e.y,this._w=s)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=s),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(dr(this.dot(e),-1,1)))}rotateTowards(e,t){const s=this.angleTo(e);if(s===0)return this;const r=Math.min(1,t/s);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const s=e._x,r=e._y,i=e._z,o=e._w,a=t._x,l=t._y,c=t._z,u=t._w;return this._x=s*u+o*a+r*c-i*l,this._y=r*u+o*l+i*a-s*c,this._z=i*u+o*c+s*l-r*a,this._w=o*u-s*a-r*l-i*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const s=this._x,r=this._y,i=this._z,o=this._w;let a=o*e._w+s*e._x+r*e._y+i*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=o,this._x=s,this._y=r,this._z=i,this;const l=1-a*a;if(l<=Number.EPSILON){const p=1-t;return this._w=p*o+t*this._w,this._x=p*s+t*this._x,this._y=p*r+t*this._y,this._z=p*i+t*this._z,this.normalize(),this}const c=Math.sqrt(l),u=Math.atan2(c,a),h=Math.sin((1-t)*u)/c,d=Math.sin(t*u)/c;return this._w=o*h+this._w*d,this._x=s*h+this._x*d,this._y=r*h+this._y*d,this._z=i*h+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,s){return this.copy(e).slerp(t,s)}random(){const e=Math.random(),t=Math.sqrt(1-e),s=Math.sqrt(e),r=2*Math.PI*Math.random(),i=2*Math.PI*Math.random();return this.set(t*Math.cos(r),s*Math.sin(i),s*Math.cos(i),t*Math.sin(r))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class fe{constructor(e=0,t=0,s=0){fe.prototype.isVector3=!0,this.x=e,this.y=t,this.z=s}set(e,t,s){return s===void 0&&(s=this.z),this.x=e,this.y=t,this.z=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(I3.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(I3.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,s=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*s+i[6]*r,this.y=i[1]*t+i[4]*s+i[7]*r,this.z=i[2]*t+i[5]*s+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,s=this.y,r=this.z,i=e.elements,o=1/(i[3]*t+i[7]*s+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*s+i[8]*r+i[12])*o,this.y=(i[1]*t+i[5]*s+i[9]*r+i[13])*o,this.z=(i[2]*t+i[6]*s+i[10]*r+i[14])*o,this}applyQuaternion(e){const t=this.x,s=this.y,r=this.z,i=e.x,o=e.y,a=e.z,l=e.w,c=2*(o*r-a*s),u=2*(a*t-i*r),h=2*(i*s-o*t);return this.x=t+l*c+o*h-a*u,this.y=s+l*u+a*c-i*h,this.z=r+l*h+i*u-o*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,s=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*s+i[8]*r,this.y=i[1]*t+i[5]*s+i[9]*r,this.z=i[2]*t+i[6]*s+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Math.max(e,Math.min(t,s)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const s=e.x,r=e.y,i=e.z,o=t.x,a=t.y,l=t.z;return this.x=r*l-i*a,this.y=i*o-s*l,this.z=s*a-r*o,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const s=e.dot(this)/t;return this.copy(e).multiplyScalar(s)}projectOnPlane(e){return s1.copy(this).projectOnVector(e),this.sub(s1)}reflect(e){return this.sub(s1.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(dr(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y,r=this.z-e.z;return t*t+s*s+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,s){const r=Math.sin(t)*e;return this.x=r*Math.sin(s),this.y=Math.cos(t)*e,this.z=r*Math.cos(s),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,s){return this.x=e*Math.sin(t),this.y=s,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),s=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=s,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=(Math.random()-.5)*2,t=Math.random()*Math.PI*2,s=Math.sqrt(1-e**2);return this.x=s*Math.cos(t),this.y=s*Math.sin(t),this.z=e,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const s1=new fe,I3=new Cp;class _p{constructor(e=new fe(1/0,1/0,1/0),t=new fe(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,s=e.length;tthis.max.x||e.ythis.max.y||e.zthis.max.z)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return!(e.max.xthis.max.x||e.max.ythis.max.y||e.max.zthis.max.z)}intersectsSphere(e){return this.clampPoint(e.center,oi),oi.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,s;return e.normal.x>0?(t=e.normal.x*this.min.x,s=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,s=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,s+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,s+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,s+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,s+=e.normal.z*this.min.z),t<=-e.constant&&s>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(bh),Xp.subVectors(this.max,bh),Ql.subVectors(e.a,bh),ec.subVectors(e.b,bh),tc.subVectors(e.c,bh),Oo.subVectors(ec,Ql),zo.subVectors(tc,ec),La.subVectors(Ql,tc);let t=[0,-Oo.z,Oo.y,0,-zo.z,zo.y,0,-La.z,La.y,Oo.z,0,-Oo.x,zo.z,0,-zo.x,La.z,0,-La.x,-Oo.y,Oo.x,0,-zo.y,zo.x,0,-La.y,La.x,0];return!r1(t,Ql,ec,tc,Xp)||(t=[1,0,0,0,1,0,0,0,1],!r1(t,Ql,ec,tc,Xp))?!1:(Kp.crossVectors(Oo,zo),t=[Kp.x,Kp.y,Kp.z],r1(t,Ql,ec,tc,Xp))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,oi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(oi).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(co[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),co[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),co[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),co[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),co[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),co[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),co[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),co[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(co),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const co=[new fe,new fe,new fe,new fe,new fe,new fe,new fe,new fe],oi=new fe,qp=new _p,Ql=new fe,ec=new fe,tc=new fe,Oo=new fe,zo=new fe,La=new fe,bh=new fe,Xp=new fe,Kp=new fe,Fa=new fe;function r1(n,e,t,s,r){for(let i=0,o=n.length-3;i<=o;i+=3){Fa.fromArray(n,i);const a=r.x*Math.abs(Fa.x)+r.y*Math.abs(Fa.y)+r.z*Math.abs(Fa.z),l=e.dot(Fa),c=t.dot(Fa),u=s.dot(Fa);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>a)return!1}return!0}const phe=new _p,yh=new fe,i1=new fe;class ub{constructor(e=new fe,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const s=this.center;t!==void 0?s.copy(t):phe.setFromPoints(e).getCenter(s);let r=0;for(let i=0,o=e.length;ithis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;yh.subVectors(e,this.center);const t=yh.lengthSq();if(t>this.radius*this.radius){const s=Math.sqrt(t),r=(s-this.radius)*.5;this.center.addScaledVector(yh,r/s),this.radius+=r}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(i1.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(yh.copy(e.center).add(i1)),this.expandByPoint(yh.copy(e.center).sub(i1))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const uo=new fe,o1=new fe,jp=new fe,Bo=new fe,a1=new fe,Yp=new fe,l1=new fe;class fhe{constructor(e=new fe,t=new fe(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,uo)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const s=t.dot(this.direction);return s<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,s)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=uo.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(uo.copy(this.origin).addScaledVector(this.direction,t),uo.distanceToSquared(e))}distanceSqToSegment(e,t,s,r){o1.copy(e).add(t).multiplyScalar(.5),jp.copy(t).sub(e).normalize(),Bo.copy(this.origin).sub(o1);const i=e.distanceTo(t)*.5,o=-this.direction.dot(jp),a=Bo.dot(this.direction),l=-Bo.dot(jp),c=Bo.lengthSq(),u=Math.abs(1-o*o);let h,d,p,f;if(u>0)if(h=o*l-a,d=o*a-l,f=i*u,h>=0)if(d>=-f)if(d<=f){const x=1/u;h*=x,d*=x,p=h*(h+o*d+2*a)+d*(o*h+d+2*l)+c}else d=i,h=Math.max(0,-(o*d+a)),p=-h*h+d*(d+2*l)+c;else d=-i,h=Math.max(0,-(o*d+a)),p=-h*h+d*(d+2*l)+c;else d<=-f?(h=Math.max(0,-(-o*i+a)),d=h>0?-i:Math.min(Math.max(-i,-l),i),p=-h*h+d*(d+2*l)+c):d<=f?(h=0,d=Math.min(Math.max(-i,-l),i),p=d*(d+2*l)+c):(h=Math.max(0,-(o*i+a)),d=h>0?i:Math.min(Math.max(-i,-l),i),p=-h*h+d*(d+2*l)+c);else d=o>0?-i:i,h=Math.max(0,-(o*d+a)),p=-h*h+d*(d+2*l)+c;return s&&s.copy(this.origin).addScaledVector(this.direction,h),r&&r.copy(o1).addScaledVector(jp,d),p}intersectSphere(e,t){uo.subVectors(e.center,this.origin);const s=uo.dot(this.direction),r=uo.dot(uo)-s*s,i=e.radius*e.radius;if(r>i)return null;const o=Math.sqrt(i-r),a=s-o,l=s+o;return l<0?null:a<0?this.at(l,t):this.at(a,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const s=-(this.origin.dot(e.normal)+e.constant)/t;return s>=0?s:null}intersectPlane(e,t){const s=this.distanceToPlane(e);return s===null?null:this.at(s,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let s,r,i,o,a,l;const c=1/this.direction.x,u=1/this.direction.y,h=1/this.direction.z,d=this.origin;return c>=0?(s=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(s=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),u>=0?(i=(e.min.y-d.y)*u,o=(e.max.y-d.y)*u):(i=(e.max.y-d.y)*u,o=(e.min.y-d.y)*u),s>o||i>r||((i>s||isNaN(s))&&(s=i),(o=0?(a=(e.min.z-d.z)*h,l=(e.max.z-d.z)*h):(a=(e.max.z-d.z)*h,l=(e.min.z-d.z)*h),s>l||a>r)||((a>s||s!==s)&&(s=a),(l=0?s:r,t)}intersectsBox(e){return this.intersectBox(e,uo)!==null}intersectTriangle(e,t,s,r,i){a1.subVectors(t,e),Yp.subVectors(s,e),l1.crossVectors(a1,Yp);let o=this.direction.dot(l1),a;if(o>0){if(r)return null;a=1}else if(o<0)a=-1,o=-o;else return null;Bo.subVectors(this.origin,e);const l=a*this.direction.dot(Yp.crossVectors(Bo,Yp));if(l<0)return null;const c=a*this.direction.dot(a1.cross(Bo));if(c<0||l+c>o)return null;const u=-a*Bo.dot(l1);return u<0?null:this.at(u/o,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class ks{constructor(e,t,s,r,i,o,a,l,c,u,h,d,p,f,x,m){ks.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,s,r,i,o,a,l,c,u,h,d,p,f,x,m)}set(e,t,s,r,i,o,a,l,c,u,h,d,p,f,x,m){const g=this.elements;return g[0]=e,g[4]=t,g[8]=s,g[12]=r,g[1]=i,g[5]=o,g[9]=a,g[13]=l,g[2]=c,g[6]=u,g[10]=h,g[14]=d,g[3]=p,g[7]=f,g[11]=x,g[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new ks().fromArray(this.elements)}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],t[9]=s[9],t[10]=s[10],t[11]=s[11],t[12]=s[12],t[13]=s[13],t[14]=s[14],t[15]=s[15],this}copyPosition(e){const t=this.elements,s=e.elements;return t[12]=s[12],t[13]=s[13],t[14]=s[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,s){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this}makeBasis(e,t,s){return this.set(e.x,t.x,s.x,0,e.y,t.y,s.y,0,e.z,t.z,s.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,s=e.elements,r=1/nc.setFromMatrixColumn(e,0).length(),i=1/nc.setFromMatrixColumn(e,1).length(),o=1/nc.setFromMatrixColumn(e,2).length();return t[0]=s[0]*r,t[1]=s[1]*r,t[2]=s[2]*r,t[3]=0,t[4]=s[4]*i,t[5]=s[5]*i,t[6]=s[6]*i,t[7]=0,t[8]=s[8]*o,t[9]=s[9]*o,t[10]=s[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,s=e.x,r=e.y,i=e.z,o=Math.cos(s),a=Math.sin(s),l=Math.cos(r),c=Math.sin(r),u=Math.cos(i),h=Math.sin(i);if(e.order==="XYZ"){const d=o*u,p=o*h,f=a*u,x=a*h;t[0]=l*u,t[4]=-l*h,t[8]=c,t[1]=p+f*c,t[5]=d-x*c,t[9]=-a*l,t[2]=x-d*c,t[6]=f+p*c,t[10]=o*l}else if(e.order==="YXZ"){const d=l*u,p=l*h,f=c*u,x=c*h;t[0]=d+x*a,t[4]=f*a-p,t[8]=o*c,t[1]=o*h,t[5]=o*u,t[9]=-a,t[2]=p*a-f,t[6]=x+d*a,t[10]=o*l}else if(e.order==="ZXY"){const d=l*u,p=l*h,f=c*u,x=c*h;t[0]=d-x*a,t[4]=-o*h,t[8]=f+p*a,t[1]=p+f*a,t[5]=o*u,t[9]=x-d*a,t[2]=-o*c,t[6]=a,t[10]=o*l}else if(e.order==="ZYX"){const d=o*u,p=o*h,f=a*u,x=a*h;t[0]=l*u,t[4]=f*c-p,t[8]=d*c+x,t[1]=l*h,t[5]=x*c+d,t[9]=p*c-f,t[2]=-c,t[6]=a*l,t[10]=o*l}else if(e.order==="YZX"){const d=o*l,p=o*c,f=a*l,x=a*c;t[0]=l*u,t[4]=x-d*h,t[8]=f*h+p,t[1]=h,t[5]=o*u,t[9]=-a*u,t[2]=-c*u,t[6]=p*h+f,t[10]=d-x*h}else if(e.order==="XZY"){const d=o*l,p=o*c,f=a*l,x=a*c;t[0]=l*u,t[4]=-h,t[8]=c*u,t[1]=d*h+x,t[5]=o*u,t[9]=p*h-f,t[2]=f*h-p,t[6]=a*u,t[10]=x*h+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(mhe,e,ghe)}lookAt(e,t,s){const r=this.elements;return Cr.subVectors(e,t),Cr.lengthSq()===0&&(Cr.z=1),Cr.normalize(),Uo.crossVectors(s,Cr),Uo.lengthSq()===0&&(Math.abs(s.z)===1?Cr.x+=1e-4:Cr.z+=1e-4,Cr.normalize(),Uo.crossVectors(s,Cr)),Uo.normalize(),Zp.crossVectors(Cr,Uo),r[0]=Uo.x,r[4]=Zp.x,r[8]=Cr.x,r[1]=Uo.y,r[5]=Zp.y,r[9]=Cr.y,r[2]=Uo.z,r[6]=Zp.z,r[10]=Cr.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,r=t.elements,i=this.elements,o=s[0],a=s[4],l=s[8],c=s[12],u=s[1],h=s[5],d=s[9],p=s[13],f=s[2],x=s[6],m=s[10],g=s[14],v=s[3],b=s[7],y=s[11],w=s[15],C=r[0],T=r[4],E=r[8],R=r[12],_=r[1],k=r[5],F=r[9],B=r[13],M=r[2],P=r[6],L=r[10],q=r[14],U=r[3],X=r[7],K=r[11],J=r[15];return i[0]=o*C+a*_+l*M+c*U,i[4]=o*T+a*k+l*P+c*X,i[8]=o*E+a*F+l*L+c*K,i[12]=o*R+a*B+l*q+c*J,i[1]=u*C+h*_+d*M+p*U,i[5]=u*T+h*k+d*P+p*X,i[9]=u*E+h*F+d*L+p*K,i[13]=u*R+h*B+d*q+p*J,i[2]=f*C+x*_+m*M+g*U,i[6]=f*T+x*k+m*P+g*X,i[10]=f*E+x*F+m*L+g*K,i[14]=f*R+x*B+m*q+g*J,i[3]=v*C+b*_+y*M+w*U,i[7]=v*T+b*k+y*P+w*X,i[11]=v*E+b*F+y*L+w*K,i[15]=v*R+b*B+y*q+w*J,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[4],r=e[8],i=e[12],o=e[1],a=e[5],l=e[9],c=e[13],u=e[2],h=e[6],d=e[10],p=e[14],f=e[3],x=e[7],m=e[11],g=e[15];return f*(+i*l*h-r*c*h-i*a*d+s*c*d+r*a*p-s*l*p)+x*(+t*l*p-t*c*d+i*o*d-r*o*p+r*c*u-i*l*u)+m*(+t*c*h-t*a*p-i*o*h+s*o*p+i*a*u-s*c*u)+g*(-r*a*u-t*l*h+t*a*d+r*o*h-s*o*d+s*l*u)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,s){const r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=s),this}invert(){const e=this.elements,t=e[0],s=e[1],r=e[2],i=e[3],o=e[4],a=e[5],l=e[6],c=e[7],u=e[8],h=e[9],d=e[10],p=e[11],f=e[12],x=e[13],m=e[14],g=e[15],v=h*m*c-x*d*c+x*l*p-a*m*p-h*l*g+a*d*g,b=f*d*c-u*m*c-f*l*p+o*m*p+u*l*g-o*d*g,y=u*x*c-f*h*c+f*a*p-o*x*p-u*a*g+o*h*g,w=f*h*l-u*x*l-f*a*d+o*x*d+u*a*m-o*h*m,C=t*v+s*b+r*y+i*w;if(C===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const T=1/C;return e[0]=v*T,e[1]=(x*d*i-h*m*i-x*r*p+s*m*p+h*r*g-s*d*g)*T,e[2]=(a*m*i-x*l*i+x*r*c-s*m*c-a*r*g+s*l*g)*T,e[3]=(h*l*i-a*d*i-h*r*c+s*d*c+a*r*p-s*l*p)*T,e[4]=b*T,e[5]=(u*m*i-f*d*i+f*r*p-t*m*p-u*r*g+t*d*g)*T,e[6]=(f*l*i-o*m*i-f*r*c+t*m*c+o*r*g-t*l*g)*T,e[7]=(o*d*i-u*l*i+u*r*c-t*d*c-o*r*p+t*l*p)*T,e[8]=y*T,e[9]=(f*h*i-u*x*i-f*s*p+t*x*p+u*s*g-t*h*g)*T,e[10]=(o*x*i-f*a*i+f*s*c-t*x*c-o*s*g+t*a*g)*T,e[11]=(u*a*i-o*h*i-u*s*c+t*h*c+o*s*p-t*a*p)*T,e[12]=w*T,e[13]=(u*x*r-f*h*r+f*s*d-t*x*d-u*s*m+t*h*m)*T,e[14]=(f*a*r-o*x*r-f*s*l+t*x*l+o*s*m-t*a*m)*T,e[15]=(o*h*r-u*a*r+u*s*l-t*h*l-o*s*d+t*a*d)*T,this}scale(e){const t=this.elements,s=e.x,r=e.y,i=e.z;return t[0]*=s,t[4]*=r,t[8]*=i,t[1]*=s,t[5]*=r,t[9]*=i,t[2]*=s,t[6]*=r,t[10]*=i,t[3]*=s,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],s=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,s,r))}makeTranslation(e,t,s){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,s,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),s=Math.sin(e);return this.set(1,0,0,0,0,t,-s,0,0,s,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,0,s,0,0,1,0,0,-s,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,0,s,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const s=Math.cos(t),r=Math.sin(t),i=1-s,o=e.x,a=e.y,l=e.z,c=i*o,u=i*a;return this.set(c*o+s,c*a-r*l,c*l+r*a,0,c*a+r*l,u*a+s,u*l-r*o,0,c*l-r*a,u*l+r*o,i*l*l+s,0,0,0,0,1),this}makeScale(e,t,s){return this.set(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1),this}makeShear(e,t,s,r,i,o){return this.set(1,s,i,0,e,1,o,0,t,r,1,0,0,0,0,1),this}compose(e,t,s){const r=this.elements,i=t._x,o=t._y,a=t._z,l=t._w,c=i+i,u=o+o,h=a+a,d=i*c,p=i*u,f=i*h,x=o*u,m=o*h,g=a*h,v=l*c,b=l*u,y=l*h,w=s.x,C=s.y,T=s.z;return r[0]=(1-(x+g))*w,r[1]=(p+y)*w,r[2]=(f-b)*w,r[3]=0,r[4]=(p-y)*C,r[5]=(1-(d+g))*C,r[6]=(m+v)*C,r[7]=0,r[8]=(f+b)*T,r[9]=(m-v)*T,r[10]=(1-(d+x))*T,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,s){const r=this.elements;let i=nc.set(r[0],r[1],r[2]).length();const o=nc.set(r[4],r[5],r[6]).length(),a=nc.set(r[8],r[9],r[10]).length();this.determinant()<0&&(i=-i),e.x=r[12],e.y=r[13],e.z=r[14],ai.copy(this);const c=1/i,u=1/o,h=1/a;return ai.elements[0]*=c,ai.elements[1]*=c,ai.elements[2]*=c,ai.elements[4]*=u,ai.elements[5]*=u,ai.elements[6]*=u,ai.elements[8]*=h,ai.elements[9]*=h,ai.elements[10]*=h,t.setFromRotationMatrix(ai),s.x=i,s.y=o,s.z=a,this}makePerspective(e,t,s,r,i,o,a=Co){const l=this.elements,c=2*i/(t-e),u=2*i/(s-r),h=(t+e)/(t-e),d=(s+r)/(s-r);let p,f;if(a===Co)p=-(o+i)/(o-i),f=-2*o*i/(o-i);else if(a===h0)p=-o/(o-i),f=-o*i/(o-i);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=c,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=u,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=f,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,s,r,i,o,a=Co){const l=this.elements,c=1/(t-e),u=1/(s-r),h=1/(o-i),d=(t+e)*c,p=(s+r)*u;let f,x;if(a===Co)f=(o+i)*h,x=-2*h;else if(a===h0)f=i*h,x=-1*h;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=2*c,l[4]=0,l[8]=0,l[12]=-d,l[1]=0,l[5]=2*u,l[9]=0,l[13]=-p,l[2]=0,l[6]=0,l[10]=x,l[14]=-f,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,s=e.elements;for(let r=0;r<16;r++)if(t[r]!==s[r])return!1;return!0}fromArray(e,t=0){for(let s=0;s<16;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e[t+9]=s[9],e[t+10]=s[10],e[t+11]=s[11],e[t+12]=s[12],e[t+13]=s[13],e[t+14]=s[14],e[t+15]=s[15],e}}const nc=new fe,ai=new ks,mhe=new fe(0,0,0),ghe=new fe(1,1,1),Uo=new fe,Zp=new fe,Cr=new fe,E3=new ks,k3=new Cp;class og{constructor(e=0,t=0,s=0,r=og.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=s,this._order=r}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,s,r=this._order){return this._x=e,this._y=t,this._z=s,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,s=!0){const r=e.elements,i=r[0],o=r[4],a=r[8],l=r[1],c=r[5],u=r[9],h=r[2],d=r[6],p=r[10];switch(t){case"XYZ":this._y=Math.asin(dr(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,p),this._z=Math.atan2(-o,i)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-dr(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,p),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-h,i),this._z=0);break;case"ZXY":this._x=Math.asin(dr(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-h,p),this._z=Math.atan2(-o,c)):(this._y=0,this._z=Math.atan2(l,i));break;case"ZYX":this._y=Math.asin(-dr(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(d,p),this._z=Math.atan2(l,i)):(this._x=0,this._z=Math.atan2(-o,c));break;case"YZX":this._z=Math.asin(dr(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,c),this._y=Math.atan2(-h,i)):(this._x=0,this._y=Math.atan2(a,p));break;case"XZY":this._z=Math.asin(-dr(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(a,i)):(this._x=Math.atan2(-u,p),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,s===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return E3.makeRotationFromQuaternion(e),this.setFromRotationMatrix(E3,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return k3.setFromEuler(this),this.setFromQuaternion(k3,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}og.DEFAULT_ORDER="XYZ";class Qk{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let s=0;s0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.isInstancedMesh&&(r.type="InstancedMesh",r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type="BatchedMesh",r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.visibility=this._visibility,r.active=this._active,r.bounds=this._bounds.map(a=>({boxInitialized:a.boxInitialized,boxMin:a.box.min.toArray(),boxMax:a.box.max.toArray(),sphereInitialized:a.sphereInitialized,sphereRadius:a.sphere.radius,sphereCenter:a.sphere.center.toArray()})),r.maxGeometryCount=this._maxGeometryCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.geometryCount=this._geometryCount,r.matricesTexture=this._matricesTexture.toJSON(e),this.boundingSphere!==null&&(r.boundingSphere={center:r.boundingSphere.center.toArray(),radius:r.boundingSphere.radius}),this.boundingBox!==null&&(r.boundingBox={min:r.boundingBox.min.toArray(),max:r.boundingBox.max.toArray()}));function i(a,l){return a[l.uuid]===void 0&&(a[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const l=a.shapes;if(Array.isArray(l))for(let c=0,u=l.length;c0){r.children=[];for(let a=0;a0){r.animations=[];for(let a=0;a0&&(s.geometries=a),l.length>0&&(s.materials=l),c.length>0&&(s.textures=c),u.length>0&&(s.images=u),h.length>0&&(s.shapes=h),d.length>0&&(s.skeletons=d),p.length>0&&(s.animations=p),f.length>0&&(s.nodes=f)}return s.object=r,s;function o(a){const l=[];for(const c in a){const u=a[c];delete u.metadata,l.push(u)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let s=0;s0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,s,r,i){li.subVectors(r,t),po.subVectors(s,t),c1.subVectors(e,t);const o=li.dot(li),a=li.dot(po),l=li.dot(c1),c=po.dot(po),u=po.dot(c1),h=o*c-a*a;if(h===0)return i.set(0,0,0),null;const d=1/h,p=(c*l-a*u)*d,f=(o*u-a*l)*d;return i.set(1-p-f,f,p)}static containsPoint(e,t,s,r){return this.getBarycoord(e,t,s,r,fo)===null?!1:fo.x>=0&&fo.y>=0&&fo.x+fo.y<=1}static getInterpolation(e,t,s,r,i,o,a,l){return this.getBarycoord(e,t,s,r,fo)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(i,fo.x),l.addScaledVector(o,fo.y),l.addScaledVector(a,fo.z),l)}static isFrontFacing(e,t,s,r){return li.subVectors(s,t),po.subVectors(e,t),li.cross(po).dot(r)<0}set(e,t,s){return this.a.copy(e),this.b.copy(t),this.c.copy(s),this}setFromPointsAndIndices(e,t,s,r){return this.a.copy(e[t]),this.b.copy(e[s]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,s,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,s),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return li.subVectors(this.c,this.b),po.subVectors(this.a,this.b),li.cross(po).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Ui.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Ui.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,r,i){return Ui.getInterpolation(e,this.a,this.b,this.c,t,s,r,i)}containsPoint(e){return Ui.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Ui.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const s=this.a,r=this.b,i=this.c;let o,a;rc.subVectors(r,s),ic.subVectors(i,s),u1.subVectors(e,s);const l=rc.dot(u1),c=ic.dot(u1);if(l<=0&&c<=0)return t.copy(s);h1.subVectors(e,r);const u=rc.dot(h1),h=ic.dot(h1);if(u>=0&&h<=u)return t.copy(r);const d=l*h-u*c;if(d<=0&&l>=0&&u<=0)return o=l/(l-u),t.copy(s).addScaledVector(rc,o);d1.subVectors(e,i);const p=rc.dot(d1),f=ic.dot(d1);if(f>=0&&p<=f)return t.copy(i);const x=p*c-l*f;if(x<=0&&c>=0&&f<=0)return a=c/(c-f),t.copy(s).addScaledVector(ic,a);const m=u*f-p*h;if(m<=0&&h-u>=0&&p-f>=0)return $3.subVectors(i,r),a=(h-u)/(h-u+(p-f)),t.copy(r).addScaledVector($3,a);const g=1/(m+x+d);return o=x*g,a=d*g,t.copy(s).addScaledVector(rc,o).addScaledVector(ic,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const eA={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Vo={h:0,s:0,l:0},Qp={h:0,s:0,l:0};function p1(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class un{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(t===void 0&&s===void 0){const r=e;r&&r.isColor?this.copy(r):typeof r=="number"?this.setHex(r):typeof r=="string"&&this.setStyle(r)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Is){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,cn.toWorkingColorSpace(this,t),this}setRGB(e,t,s,r=cn.workingColorSpace){return this.r=e,this.g=t,this.b=s,cn.toWorkingColorSpace(this,r),this}setHSL(e,t,s,r=cn.workingColorSpace){if(e=ohe(e,1),t=dr(t,0,1),s=dr(s,0,1),t===0)this.r=this.g=this.b=s;else{const i=s<=.5?s*(1+t):s+t-s*t,o=2*s-i;this.r=p1(o,i,e+1/3),this.g=p1(o,i,e),this.b=p1(o,i,e-1/3)}return cn.toWorkingColorSpace(this,r),this}setStyle(e,t=Is){function s(i){i!==void 0&&parseFloat(i)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i;const o=r[1],a=r[2];switch(o){case"rgb":case"rgba":if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return s(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return s(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case"hsl":case"hsla":if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return s(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){const i=r[1],o=i.length;if(o===3)return this.setRGB(parseInt(i.charAt(0),16)/15,parseInt(i.charAt(1),16)/15,parseInt(i.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(i,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Is){const s=eA[e.toLowerCase()];return s!==void 0?this.setHex(s,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Ic(e.r),this.g=Ic(e.g),this.b=Ic(e.b),this}copyLinearToSRGB(e){return this.r=t1(e.r),this.g=t1(e.g),this.b=t1(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Is){return cn.fromWorkingColorSpace(Ps.copy(this),e),Math.round(dr(Ps.r*255,0,255))*65536+Math.round(dr(Ps.g*255,0,255))*256+Math.round(dr(Ps.b*255,0,255))}getHexString(e=Is){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=cn.workingColorSpace){cn.fromWorkingColorSpace(Ps.copy(this),t);const s=Ps.r,r=Ps.g,i=Ps.b,o=Math.max(s,r,i),a=Math.min(s,r,i);let l,c;const u=(a+o)/2;if(a===o)l=0,c=0;else{const h=o-a;switch(c=u<=.5?h/(o+a):h/(2-o-a),o){case s:l=(r-i)/h+(r0!=e>0&&this.version++,this._alphaTest=e}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const s=e[t];if(s===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const r=this[t];if(r===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(s):r&&r.isVector3&&s&&s.isVector3?r.copy(s):this[t]=s}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const s={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};s.uuid=this.uuid,s.type=this.type,this.name!==""&&(s.name=this.name),this.color&&this.color.isColor&&(s.color=this.color.getHex()),this.roughness!==void 0&&(s.roughness=this.roughness),this.metalness!==void 0&&(s.metalness=this.metalness),this.sheen!==void 0&&(s.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(s.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(s.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(s.emissive=this.emissive.getHex()),this.emissiveIntensity&&this.emissiveIntensity!==1&&(s.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(s.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(s.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(s.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(s.shininess=this.shininess),this.clearcoat!==void 0&&(s.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(s.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(s.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(s.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(s.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,s.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.iridescence!==void 0&&(s.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(s.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(s.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(s.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(s.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(s.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(s.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(s.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(s.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(s.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(s.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(s.lightMap=this.lightMap.toJSON(e).uuid,s.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(s.aoMap=this.aoMap.toJSON(e).uuid,s.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(s.bumpMap=this.bumpMap.toJSON(e).uuid,s.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(s.normalMap=this.normalMap.toJSON(e).uuid,s.normalMapType=this.normalMapType,s.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(s.displacementMap=this.displacementMap.toJSON(e).uuid,s.displacementScale=this.displacementScale,s.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(s.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(s.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(s.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(s.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(s.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(s.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(s.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(s.combine=this.combine)),this.envMapIntensity!==void 0&&(s.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(s.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(s.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(s.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(s.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(s.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(s.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(s.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(s.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(s.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(s.size=this.size),this.shadowSide!==null&&(s.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(s.sizeAttenuation=this.sizeAttenuation),this.blending!==_c&&(s.blending=this.blending),this.side!==pa&&(s.side=this.side),this.vertexColors===!0&&(s.vertexColors=!0),this.opacity<1&&(s.opacity=this.opacity),this.transparent===!0&&(s.transparent=!0),this.blendSrc!==Mx&&(s.blendSrc=this.blendSrc),this.blendDst!==Nx&&(s.blendDst=this.blendDst),this.blendEquation!==Za&&(s.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(s.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(s.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(s.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(s.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(s.blendAlpha=this.blendAlpha),this.depthFunc!==a0&&(s.depthFunc=this.depthFunc),this.depthTest===!1&&(s.depthTest=this.depthTest),this.depthWrite===!1&&(s.depthWrite=this.depthWrite),this.colorWrite===!1&&(s.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(s.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==b3&&(s.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(s.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Zl&&(s.stencilFail=this.stencilFail),this.stencilZFail!==Zl&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==Zl&&(s.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(s.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(s.rotation=this.rotation),this.polygonOffset===!0&&(s.polygonOffset=!0),this.polygonOffsetFactor!==0&&(s.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(s.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(s.linewidth=this.linewidth),this.dashSize!==void 0&&(s.dashSize=this.dashSize),this.gapSize!==void 0&&(s.gapSize=this.gapSize),this.scale!==void 0&&(s.scale=this.scale),this.dithering===!0&&(s.dithering=!0),this.alphaTest>0&&(s.alphaTest=this.alphaTest),this.alphaHash===!0&&(s.alphaHash=!0),this.alphaToCoverage===!0&&(s.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(s.premultipliedAlpha=!0),this.forceSinglePass===!0&&(s.forceSinglePass=!0),this.wireframe===!0&&(s.wireframe=!0),this.wireframeLinewidth>1&&(s.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(s.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(s.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(s.flatShading=!0),this.visible===!1&&(s.visible=!1),this.toneMapped===!1&&(s.toneMapped=!1),this.fog===!1&&(s.fog=!1),Object.keys(this.userData).length>0&&(s.userData=this.userData);function r(i){const o=[];for(const a in i){const l=i[a];delete l.metadata,o.push(l)}return o}if(t){const i=r(e.textures),o=r(e.images);i.length>0&&(s.textures=i),o.length>0&&(s.images=o)}return s}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let s=null;if(t!==null){const r=t.length;s=new Array(r);for(let i=0;i!==r;++i)s[i]=t[i].clone()}return this.clippingPlanes=s,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class hb extends ag{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new un(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=Ok,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const jn=new fe,ef=new en;class Xi{constructor(e,t,s=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=s,this.usage=y3,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=yo,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return Tc("THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,s){e*=this.itemSize,s*=t.itemSize;for(let r=0,i=this.itemSize;r0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const s=this.attributes;for(const l in s){const c=s[l];e.data.attributes[l]=c.toJSON(e.data)}const r={};let i=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],u=[];for(let h=0,d=c.length;h0&&(r[l]=u,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const a=this.boundingSphere;return a!==null&&(e.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const s=e.index;s!==null&&this.setIndex(s.clone(t));const r=e.attributes;for(const c in r){const u=r[c];this.setAttribute(c,u.clone(t))}const i=e.morphAttributes;for(const c in i){const u=[],h=i[c];for(let d=0,p=h.length;d0){const r=t[s[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let i=0,o=r.length;i(e.far-e.near)**2))&&(D3.copy(i).invert(),Oa.copy(e.ray).applyMatrix4(D3),!(s.boundingBox!==null&&Oa.intersectsBox(s.boundingBox)===!1)&&this._computeIntersections(e,t,Oa)))}_computeIntersections(e,t,s){let r;const i=this.geometry,o=this.material,a=i.index,l=i.attributes.position,c=i.attributes.uv,u=i.attributes.uv1,h=i.attributes.normal,d=i.groups,p=i.drawRange;if(a!==null)if(Array.isArray(o))for(let f=0,x=d.length;ft.far?null:{distance:c,point:lf.clone(),object:n}}function cf(n,e,t,s,r,i,o,a,l,c){n.getVertexPosition(a,ac),n.getVertexPosition(l,lc),n.getVertexPosition(c,cc);const u=_he(n,e,t,s,ac,lc,cc,af);if(u){r&&(sf.fromBufferAttribute(r,a),rf.fromBufferAttribute(r,l),of.fromBufferAttribute(r,c),u.uv=Ui.getInterpolation(af,ac,lc,cc,sf,rf,of,new en)),i&&(sf.fromBufferAttribute(i,a),rf.fromBufferAttribute(i,l),of.fromBufferAttribute(i,c),u.uv1=Ui.getInterpolation(af,ac,lc,cc,sf,rf,of,new en),u.uv2=u.uv1),o&&(L3.fromBufferAttribute(o,a),F3.fromBufferAttribute(o,l),O3.fromBufferAttribute(o,c),u.normal=Ui.getInterpolation(af,ac,lc,cc,L3,F3,O3,new fe),u.normal.dot(s.direction)>0&&u.normal.multiplyScalar(-1));const h={a,b:l,c,normal:new fe,materialIndex:0};Ui.getNormal(ac,lc,cc,h.normal),u.face=h}return u}class Tp extends Ra{constructor(e=1,t=1,s=1,r=1,i=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:s,widthSegments:r,heightSegments:i,depthSegments:o};const a=this;r=Math.floor(r),i=Math.floor(i),o=Math.floor(o);const l=[],c=[],u=[],h=[];let d=0,p=0;f("z","y","x",-1,-1,s,t,e,o,i,0),f("z","y","x",1,-1,s,t,-e,o,i,1),f("x","z","y",1,1,e,s,t,r,o,2),f("x","z","y",1,-1,e,s,-t,r,o,3),f("x","y","z",1,-1,e,t,s,r,i,4),f("x","y","z",-1,-1,e,t,-s,r,i,5),this.setIndex(l),this.setAttribute("position",new Ki(c,3)),this.setAttribute("normal",new Ki(u,3)),this.setAttribute("uv",new Ki(h,2));function f(x,m,g,v,b,y,w,C,T,E,R){const _=y/T,k=w/E,F=y/2,B=w/2,M=C/2,P=T+1,L=E+1;let q=0,U=0;const X=new fe;for(let K=0;K0?1:-1,u.push(X.x,X.y,X.z),h.push(ae/T),h.push(1-K/E),q+=1}}for(let K=0;K0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const s={};for(const r in this.extensions)this.extensions[r]===!0&&(s[r]=!0);return Object.keys(s).length>0&&(t.extensions=s),t}}class rA extends Ar{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ks,this.projectionMatrix=new ks,this.projectionMatrixInverse=new ks,this.coordinateSystem=Co}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Wo=new fe,z3=new en,B3=new en;class pi extends rA{constructor(e=50,t=1,s=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=s,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=Ox*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Jg*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Ox*2*Math.atan(Math.tan(Jg*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,s){Wo.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Wo.x,Wo.y).multiplyScalar(-e/Wo.z),Wo.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(Wo.x,Wo.y).multiplyScalar(-e/Wo.z)}getViewSize(e,t){return this.getViewBounds(e,z3,B3),t.subVectors(B3,z3)}setViewOffset(e,t,s,r,i,o){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=s,this.view.offsetY=r,this.view.width=i,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Jg*.5*this.fov)/this.zoom,s=2*t,r=this.aspect*s,i=-.5*r;const o=this.view;if(this.view!==null&&this.view.enabled){const l=o.fullWidth,c=o.fullHeight;i+=o.offsetX*r/l,t-=o.offsetY*s/c,r*=o.width/l,s*=o.height/c}const a=this.filmOffset;a!==0&&(i+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-s,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const uc=-90,hc=1;class Ahe extends Ar{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const r=new pi(uc,hc,e,t);r.layers=this.layers,this.add(r);const i=new pi(uc,hc,e,t);i.layers=this.layers,this.add(i);const o=new pi(uc,hc,e,t);o.layers=this.layers,this.add(o);const a=new pi(uc,hc,e,t);a.layers=this.layers,this.add(a);const l=new pi(uc,hc,e,t);l.layers=this.layers,this.add(l);const c=new pi(uc,hc,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,r,i,o,a,l]=t;for(const c of t)this.remove(c);if(e===Co)s.up.set(0,1,0),s.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===h0)s.up.set(0,-1,0),s.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:s,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[i,o,a,l,c,u]=this.children,h=e.getRenderTarget(),d=e.getActiveCubeFace(),p=e.getActiveMipmapLevel(),f=e.xr.enabled;e.xr.enabled=!1;const x=s.texture.generateMipmaps;s.texture.generateMipmaps=!1,e.setRenderTarget(s,0,r),e.render(t,i),e.setRenderTarget(s,1,r),e.render(t,o),e.setRenderTarget(s,2,r),e.render(t,a),e.setRenderTarget(s,3,r),e.render(t,l),e.setRenderTarget(s,4,r),e.render(t,c),s.texture.generateMipmaps=x,e.setRenderTarget(s,5,r),e.render(t,u),e.setRenderTarget(h,d,p),e.xr.enabled=f,s.texture.needsPMREMUpdate=!0}}class iA extends gr{constructor(e,t,s,r,i,o,a,l,c,u){e=e!==void 0?e:[],t=t!==void 0?t:Uc,super(e,t,s,r,i,o,a,l,c,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Rhe extends Tl{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const s={width:e,height:e,depth:1},r=[s,s,s,s,s,s];t.encoding!==void 0&&(Tc("THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace."),t.colorSpace=t.encoding===hl?Is:qr),this.texture=new iA(r,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps!==void 0?t.generateMipmaps:!1,this.texture.minFilter=t.minFilter!==void 0?t.minFilter:ur}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const s={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},r=new Tp(5,5,5),i=new fa({name:"CubemapFromEquirect",uniforms:Gc(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:mr,blending:sa});i.uniforms.tEquirect.value=t;const o=new Qn(r,i),a=t.minFilter;return t.minFilter===sl&&(t.minFilter=ur),new Ahe(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t,s,r){const i=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,s,r);e.setRenderTarget(i)}}const g1=new fe,Mhe=new fe,Nhe=new Vt;class Ha{constructor(e=new fe(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,s,r){return this.normal.set(e,t,s),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,s){const r=g1.subVectors(s,t).cross(Mhe.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const s=e.delta(g1),r=this.normal.dot(s);if(r===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const i=-(e.start.dot(this.normal)+this.constant)/r;return i<0||i>1?null:t.copy(e.start).addScaledVector(s,i)}intersectsLine(e){const t=this.distanceToPoint(e.start),s=this.distanceToPoint(e.end);return t<0&&s>0||s<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const s=t||Nhe.getNormalMatrix(e),r=this.coplanarPoint(g1).applyMatrix4(e),i=this.normal.applyMatrix3(s).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const za=new ub,uf=new fe;class oA{constructor(e=new Ha,t=new Ha,s=new Ha,r=new Ha,i=new Ha,o=new Ha){this.planes=[e,t,s,r,i,o]}set(e,t,s,r,i,o){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(s),a[3].copy(r),a[4].copy(i),a[5].copy(o),this}copy(e){const t=this.planes;for(let s=0;s<6;s++)t[s].copy(e.planes[s]);return this}setFromProjectionMatrix(e,t=Co){const s=this.planes,r=e.elements,i=r[0],o=r[1],a=r[2],l=r[3],c=r[4],u=r[5],h=r[6],d=r[7],p=r[8],f=r[9],x=r[10],m=r[11],g=r[12],v=r[13],b=r[14],y=r[15];if(s[0].setComponents(l-i,d-c,m-p,y-g).normalize(),s[1].setComponents(l+i,d+c,m+p,y+g).normalize(),s[2].setComponents(l+o,d+u,m+f,y+v).normalize(),s[3].setComponents(l-o,d-u,m-f,y-v).normalize(),s[4].setComponents(l-a,d-h,m-x,y-b).normalize(),t===Co)s[5].setComponents(l+a,d+h,m+x,y+b).normalize();else if(t===h0)s[5].setComponents(a,h,x,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),za.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),za.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(za)}intersectsSprite(e){return za.center.set(0,0,0),za.radius=.7071067811865476,za.applyMatrix4(e.matrixWorld),this.intersectsSphere(za)}intersectsSphere(e){const t=this.planes,s=e.center,r=-e.radius;for(let i=0;i<6;i++)if(t[i].distanceToPoint(s)0?e.max.x:e.min.x,uf.y=r.normal.y>0?e.max.y:e.min.y,uf.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(uf)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let s=0;s<6;s++)if(t[s].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function aA(){let n=null,e=!1,t=null,s=null;function r(i,o){t(i,o),s=n.requestAnimationFrame(r)}return{start:function(){e!==!0&&t!==null&&(s=n.requestAnimationFrame(r),e=!0)},stop:function(){n.cancelAnimationFrame(s),e=!1},setAnimationLoop:function(i){t=i},setContext:function(i){n=i}}}function $he(n,e){const t=e.isWebGL2,s=new WeakMap;function r(c,u){const h=c.array,d=c.usage,p=h.byteLength,f=n.createBuffer();n.bindBuffer(u,f),n.bufferData(u,h,d),c.onUploadCallback();let x;if(h instanceof Float32Array)x=n.FLOAT;else if(h instanceof Uint16Array)if(c.isFloat16BufferAttribute)if(t)x=n.HALF_FLOAT;else throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.");else x=n.UNSIGNED_SHORT;else if(h instanceof Int16Array)x=n.SHORT;else if(h instanceof Uint32Array)x=n.UNSIGNED_INT;else if(h instanceof Int32Array)x=n.INT;else if(h instanceof Int8Array)x=n.BYTE;else if(h instanceof Uint8Array)x=n.UNSIGNED_BYTE;else if(h instanceof Uint8ClampedArray)x=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+h);return{buffer:f,type:x,bytesPerElement:h.BYTES_PER_ELEMENT,version:c.version,size:p}}function i(c,u,h){const d=u.array,p=u._updateRange,f=u.updateRanges;if(n.bindBuffer(h,c),p.count===-1&&f.length===0&&n.bufferSubData(h,0,d),f.length!==0){for(let x=0,m=f.length;x 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`,Yhe=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,Zhe=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,Jhe=`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,Qhe=`#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`,ede=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`,tde=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) + varying vec3 vColor; +#endif`,nde=`#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif`,sde=`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +float luminance( const in vec3 rgb ) { + const vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 ); + return dot( weights, rgb ); +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`,rde=`#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`,ide=`vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`,ode=`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,ade=`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`,lde=`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,cde=`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,ude="gl_FragColor = linearToOutputTexel( gl_FragColor );",hde=` +const mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3( + vec3( 0.8224621, 0.177538, 0.0 ), + vec3( 0.0331941, 0.9668058, 0.0 ), + vec3( 0.0170827, 0.0723974, 0.9105199 ) +); +const mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3( + vec3( 1.2249401, - 0.2249404, 0.0 ), + vec3( - 0.0420569, 1.0420571, 0.0 ), + vec3( - 0.0196376, - 0.0786361, 1.0982735 ) +); +vec4 LinearSRGBToLinearDisplayP3( in vec4 value ) { + return vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a ); +} +vec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) { + return vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a ); +} +vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +} +vec4 LinearToLinear( in vec4 value ) { + return value; +} +vec4 LinearTosRGB( in vec4 value ) { + return sRGBTransferOETF( value ); +}`,dde=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`,pde=`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`,fde=`#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`,mde=`#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`,gde=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,xde=`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,vde=`#ifdef USE_FOG + varying float vFogDepth; +#endif`,bde=`#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`,yde=`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,wde=`#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`,Sde=`#ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + reflectedLight.indirectDiffuse += lightMapIrradiance; +#endif`,Cde=`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,_de=`LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`,Tde=`varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,Ide=`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + #if defined ( LEGACY_LIGHTS ) + if ( cutoffDistance > 0.0 && decayExponent > 0.0 ) { + return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent ); + } + return 1.0; + #else + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; + #endif +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`,Ede=`#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`,kde=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,Ade=`varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,Rde=`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,Mde=`varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,Nde=`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`,$de=`struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,Dde=` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,Pde=`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,Lde=`#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`,Fde=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT ) + gl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,Ode=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,zde=`#ifdef USE_LOGDEPTHBUF + #ifdef USE_LOGDEPTHBUF_EXT + varying float vFragDepth; + varying float vIsPerspective; + #else + uniform float logDepthBufFC; + #endif +#endif`,Bde=`#ifdef USE_LOGDEPTHBUF + #ifdef USE_LOGDEPTHBUF_EXT + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); + #else + if ( isPerspectiveMatrix( projectionMatrix ) ) { + gl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0; + gl_Position.z *= gl_Position.w; + } + #endif +#endif`,Ude=`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w ); + + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,Vde=`#ifdef USE_MAP + uniform sampler2D map; +#endif`,Wde=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`,Gde=`#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`,Hde=`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`,qde=`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,Xde=`#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`,Kde=`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + #ifdef MORPHTARGETS_TEXTURE + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } + #else + objectNormal += morphNormal0 * morphTargetInfluences[ 0 ]; + objectNormal += morphNormal1 * morphTargetInfluences[ 1 ]; + objectNormal += morphNormal2 * morphTargetInfluences[ 2 ]; + objectNormal += morphNormal3 * morphTargetInfluences[ 3 ]; + #endif +#endif`,jde=`#ifdef USE_MORPHTARGETS + uniform float morphTargetBaseInfluence; + #ifdef MORPHTARGETS_TEXTURE + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } + #else + #ifndef USE_MORPHNORMALS + uniform float morphTargetInfluences[ 8 ]; + #else + uniform float morphTargetInfluences[ 4 ]; + #endif + #endif +#endif`,Yde=`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + #ifdef MORPHTARGETS_TEXTURE + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } + #else + transformed += morphTarget0 * morphTargetInfluences[ 0 ]; + transformed += morphTarget1 * morphTargetInfluences[ 1 ]; + transformed += morphTarget2 * morphTargetInfluences[ 2 ]; + transformed += morphTarget3 * morphTargetInfluences[ 3 ]; + #ifndef USE_MORPHNORMALS + transformed += morphTarget4 * morphTargetInfluences[ 4 ]; + transformed += morphTarget5 * morphTargetInfluences[ 5 ]; + transformed += morphTarget6 * morphTargetInfluences[ 6 ]; + transformed += morphTarget7 * morphTargetInfluences[ 7 ]; + #endif + #endif +#endif`,Zde=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`,Jde=`#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,Qde=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,epe=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,tpe=`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,npe=`#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`,spe=`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`,rpe=`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`,ipe=`#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`,ope=`#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`,ape=`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,lpe=`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.; +const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. ); +const vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. ); +const float ShiftRight8 = 1. / 256.; +vec4 packDepthToRGBA( const in float v ) { + vec4 r = vec4( fract( v * PackFactors ), v ); + r.yzw -= r.xyz * ShiftRight8; return r * PackUpscale; +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors ); +} +vec2 packDepthToRG( in highp float v ) { + return packDepthToRGBA( v ).yx; +} +float unpackRGToDepth( const in highp vec2 v ) { + return unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) ); +} +vec4 pack2HalfToRGBA( vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`,cpe=`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,upe=`vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`,hpe=`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,dpe=`#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`,ppe=`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`,fpe=`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,mpe=`#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + float hard_shadow = step( compare , distribution.x ); + if (hard_shadow != 1.0 ) { + float distance = compare - distribution.x ; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return shadow; + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + vec3 lightToPosition = shadowCoord.xyz; + float dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + return ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } +#endif`,gpe=`#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,xpe=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`,vpe=`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,bpe=`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,ype=`#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`,wpe=`#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`,Spe=`#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`,Cpe=`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,_pe=`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,Tpe=`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,Ipe=`#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 OptimizedCineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,Epe=`#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`,kpe=`#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + vec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`,Ape=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,Rpe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,Mpe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`,Npe=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`;const $pe=`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,Dpe=`uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,Ppe=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,Lpe=`#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,Fpe=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,Ope=`uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`,zpe=`#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,Bpe=`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #endif +}`,Upe=`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,Vpe=`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`,Wpe=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,Gpe=`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,Hpe=`uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,qpe=`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,Xpe=`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Kpe=`uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`,jpe=`#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,Ype=`#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,Zpe=`#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`,Jpe=`#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`,Qpe=`#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`,efe=`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`,tfe=`#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,nfe=`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,sfe=`#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,rfe=`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,ife=`#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,ofe=`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,afe=`uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,lfe=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,cfe=`#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,ufe=`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`,hfe=`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 ); + vec2 scale; + scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) ); + scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`,dfe=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`,Ft={alphahash_fragment:Dhe,alphahash_pars_fragment:Phe,alphamap_fragment:Lhe,alphamap_pars_fragment:Fhe,alphatest_fragment:Ohe,alphatest_pars_fragment:zhe,aomap_fragment:Bhe,aomap_pars_fragment:Uhe,batching_pars_vertex:Vhe,batching_vertex:Whe,begin_vertex:Ghe,beginnormal_vertex:Hhe,bsdfs:qhe,iridescence_fragment:Xhe,bumpmap_pars_fragment:Khe,clipping_planes_fragment:jhe,clipping_planes_pars_fragment:Yhe,clipping_planes_pars_vertex:Zhe,clipping_planes_vertex:Jhe,color_fragment:Qhe,color_pars_fragment:ede,color_pars_vertex:tde,color_vertex:nde,common:sde,cube_uv_reflection_fragment:rde,defaultnormal_vertex:ide,displacementmap_pars_vertex:ode,displacementmap_vertex:ade,emissivemap_fragment:lde,emissivemap_pars_fragment:cde,colorspace_fragment:ude,colorspace_pars_fragment:hde,envmap_fragment:dde,envmap_common_pars_fragment:pde,envmap_pars_fragment:fde,envmap_pars_vertex:mde,envmap_physical_pars_fragment:Ede,envmap_vertex:gde,fog_vertex:xde,fog_pars_vertex:vde,fog_fragment:bde,fog_pars_fragment:yde,gradientmap_pars_fragment:wde,lightmap_fragment:Sde,lightmap_pars_fragment:Cde,lights_lambert_fragment:_de,lights_lambert_pars_fragment:Tde,lights_pars_begin:Ide,lights_toon_fragment:kde,lights_toon_pars_fragment:Ade,lights_phong_fragment:Rde,lights_phong_pars_fragment:Mde,lights_physical_fragment:Nde,lights_physical_pars_fragment:$de,lights_fragment_begin:Dde,lights_fragment_maps:Pde,lights_fragment_end:Lde,logdepthbuf_fragment:Fde,logdepthbuf_pars_fragment:Ode,logdepthbuf_pars_vertex:zde,logdepthbuf_vertex:Bde,map_fragment:Ude,map_pars_fragment:Vde,map_particle_fragment:Wde,map_particle_pars_fragment:Gde,metalnessmap_fragment:Hde,metalnessmap_pars_fragment:qde,morphcolor_vertex:Xde,morphnormal_vertex:Kde,morphtarget_pars_vertex:jde,morphtarget_vertex:Yde,normal_fragment_begin:Zde,normal_fragment_maps:Jde,normal_pars_fragment:Qde,normal_pars_vertex:epe,normal_vertex:tpe,normalmap_pars_fragment:npe,clearcoat_normal_fragment_begin:spe,clearcoat_normal_fragment_maps:rpe,clearcoat_pars_fragment:ipe,iridescence_pars_fragment:ope,opaque_fragment:ape,packing:lpe,premultiplied_alpha_fragment:cpe,project_vertex:upe,dithering_fragment:hpe,dithering_pars_fragment:dpe,roughnessmap_fragment:ppe,roughnessmap_pars_fragment:fpe,shadowmap_pars_fragment:mpe,shadowmap_pars_vertex:gpe,shadowmap_vertex:xpe,shadowmask_pars_fragment:vpe,skinbase_vertex:bpe,skinning_pars_vertex:ype,skinning_vertex:wpe,skinnormal_vertex:Spe,specularmap_fragment:Cpe,specularmap_pars_fragment:_pe,tonemapping_fragment:Tpe,tonemapping_pars_fragment:Ipe,transmission_fragment:Epe,transmission_pars_fragment:kpe,uv_pars_fragment:Ape,uv_pars_vertex:Rpe,uv_vertex:Mpe,worldpos_vertex:Npe,background_vert:$pe,background_frag:Dpe,backgroundCube_vert:Ppe,backgroundCube_frag:Lpe,cube_vert:Fpe,cube_frag:Ope,depth_vert:zpe,depth_frag:Bpe,distanceRGBA_vert:Upe,distanceRGBA_frag:Vpe,equirect_vert:Wpe,equirect_frag:Gpe,linedashed_vert:Hpe,linedashed_frag:qpe,meshbasic_vert:Xpe,meshbasic_frag:Kpe,meshlambert_vert:jpe,meshlambert_frag:Ype,meshmatcap_vert:Zpe,meshmatcap_frag:Jpe,meshnormal_vert:Qpe,meshnormal_frag:efe,meshphong_vert:tfe,meshphong_frag:nfe,meshphysical_vert:sfe,meshphysical_frag:rfe,meshtoon_vert:ife,meshtoon_frag:ofe,points_vert:afe,points_frag:lfe,shadow_vert:cfe,shadow_frag:ufe,sprite_vert:hfe,sprite_frag:dfe},We={common:{diffuse:{value:new un(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Vt},alphaMap:{value:null},alphaMapTransform:{value:new Vt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Vt}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Vt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Vt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Vt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Vt},normalScale:{value:new en(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Vt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Vt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Vt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Vt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new un(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new un(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Vt},alphaTest:{value:0},uvTransform:{value:new Vt}},sprite:{diffuse:{value:new un(16777215)},opacity:{value:1},center:{value:new en(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Vt},alphaMap:{value:null},alphaMapTransform:{value:new Vt},alphaTest:{value:0}}},Oi={basic:{uniforms:Hs([We.common,We.specularmap,We.envmap,We.aomap,We.lightmap,We.fog]),vertexShader:Ft.meshbasic_vert,fragmentShader:Ft.meshbasic_frag},lambert:{uniforms:Hs([We.common,We.specularmap,We.envmap,We.aomap,We.lightmap,We.emissivemap,We.bumpmap,We.normalmap,We.displacementmap,We.fog,We.lights,{emissive:{value:new un(0)}}]),vertexShader:Ft.meshlambert_vert,fragmentShader:Ft.meshlambert_frag},phong:{uniforms:Hs([We.common,We.specularmap,We.envmap,We.aomap,We.lightmap,We.emissivemap,We.bumpmap,We.normalmap,We.displacementmap,We.fog,We.lights,{emissive:{value:new un(0)},specular:{value:new un(1118481)},shininess:{value:30}}]),vertexShader:Ft.meshphong_vert,fragmentShader:Ft.meshphong_frag},standard:{uniforms:Hs([We.common,We.envmap,We.aomap,We.lightmap,We.emissivemap,We.bumpmap,We.normalmap,We.displacementmap,We.roughnessmap,We.metalnessmap,We.fog,We.lights,{emissive:{value:new un(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Ft.meshphysical_vert,fragmentShader:Ft.meshphysical_frag},toon:{uniforms:Hs([We.common,We.aomap,We.lightmap,We.emissivemap,We.bumpmap,We.normalmap,We.displacementmap,We.gradientmap,We.fog,We.lights,{emissive:{value:new un(0)}}]),vertexShader:Ft.meshtoon_vert,fragmentShader:Ft.meshtoon_frag},matcap:{uniforms:Hs([We.common,We.bumpmap,We.normalmap,We.displacementmap,We.fog,{matcap:{value:null}}]),vertexShader:Ft.meshmatcap_vert,fragmentShader:Ft.meshmatcap_frag},points:{uniforms:Hs([We.points,We.fog]),vertexShader:Ft.points_vert,fragmentShader:Ft.points_frag},dashed:{uniforms:Hs([We.common,We.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Ft.linedashed_vert,fragmentShader:Ft.linedashed_frag},depth:{uniforms:Hs([We.common,We.displacementmap]),vertexShader:Ft.depth_vert,fragmentShader:Ft.depth_frag},normal:{uniforms:Hs([We.common,We.bumpmap,We.normalmap,We.displacementmap,{opacity:{value:1}}]),vertexShader:Ft.meshnormal_vert,fragmentShader:Ft.meshnormal_frag},sprite:{uniforms:Hs([We.sprite,We.fog]),vertexShader:Ft.sprite_vert,fragmentShader:Ft.sprite_frag},background:{uniforms:{uvTransform:{value:new Vt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Ft.background_vert,fragmentShader:Ft.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:Ft.backgroundCube_vert,fragmentShader:Ft.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Ft.cube_vert,fragmentShader:Ft.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Ft.equirect_vert,fragmentShader:Ft.equirect_frag},distanceRGBA:{uniforms:Hs([We.common,We.displacementmap,{referencePosition:{value:new fe},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Ft.distanceRGBA_vert,fragmentShader:Ft.distanceRGBA_frag},shadow:{uniforms:Hs([We.lights,We.fog,{color:{value:new un(0)},opacity:{value:1}}]),vertexShader:Ft.shadow_vert,fragmentShader:Ft.shadow_frag}};Oi.physical={uniforms:Hs([Oi.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Vt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Vt},clearcoatNormalScale:{value:new en(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Vt},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Vt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Vt},sheen:{value:0},sheenColor:{value:new un(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Vt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Vt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Vt},transmissionSamplerSize:{value:new en},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Vt},attenuationDistance:{value:0},attenuationColor:{value:new un(0)},specularColor:{value:new un(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Vt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Vt},anisotropyVector:{value:new en},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Vt}}]),vertexShader:Ft.meshphysical_vert,fragmentShader:Ft.meshphysical_frag};const hf={r:0,b:0,g:0};function pfe(n,e,t,s,r,i,o){const a=new un(0);let l=i===!0?0:1,c,u,h=null,d=0,p=null;function f(m,g){let v=!1,b=g.isScene===!0?g.background:null;b&&b.isTexture&&(b=(g.backgroundBlurriness>0?t:e).get(b)),b===null?x(a,l):b&&b.isColor&&(x(b,1),v=!0);const y=n.xr.getEnvironmentBlendMode();y==="additive"?s.buffers.color.setClear(0,0,0,1,o):y==="alpha-blend"&&s.buffers.color.setClear(0,0,0,0,o),(n.autoClear||v)&&n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil),b&&(b.isCubeTexture||b.mapping===rg)?(u===void 0&&(u=new Qn(new Tp(1,1,1),new fa({name:"BackgroundCubeMaterial",uniforms:Gc(Oi.backgroundCube.uniforms),vertexShader:Oi.backgroundCube.vertexShader,fragmentShader:Oi.backgroundCube.fragmentShader,side:mr,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(w,C,T){this.matrixWorld.copyPosition(T.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(u)),u.material.uniforms.envMap.value=b,u.material.uniforms.flipEnvMap.value=b.isCubeTexture&&b.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=g.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,u.material.toneMapped=cn.getTransfer(b.colorSpace)!==Tn,(h!==b||d!==b.version||p!==n.toneMapping)&&(u.material.needsUpdate=!0,h=b,d=b.version,p=n.toneMapping),u.layers.enableAll(),m.unshift(u,u.geometry,u.material,0,0,null)):b&&b.isTexture&&(c===void 0&&(c=new Qn(new Jr(2,2),new fa({name:"BackgroundMaterial",uniforms:Gc(Oi.background.uniforms),vertexShader:Oi.background.vertexShader,fragmentShader:Oi.background.fragmentShader,side:pa,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(c)),c.material.uniforms.t2D.value=b,c.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,c.material.toneMapped=cn.getTransfer(b.colorSpace)!==Tn,b.matrixAutoUpdate===!0&&b.updateMatrix(),c.material.uniforms.uvTransform.value.copy(b.matrix),(h!==b||d!==b.version||p!==n.toneMapping)&&(c.material.needsUpdate=!0,h=b,d=b.version,p=n.toneMapping),c.layers.enableAll(),m.unshift(c,c.geometry,c.material,0,0,null))}function x(m,g){m.getRGB(hf,sA(n)),s.buffers.color.setClear(hf.r,hf.g,hf.b,g,o)}return{getClearColor:function(){return a},setClearColor:function(m,g=1){a.set(m),l=g,x(a,l)},getClearAlpha:function(){return l},setClearAlpha:function(m){l=m,x(a,l)},render:f}}function ffe(n,e,t,s){const r=n.getParameter(n.MAX_VERTEX_ATTRIBS),i=s.isWebGL2?null:e.get("OES_vertex_array_object"),o=s.isWebGL2||i!==null,a={},l=m(null);let c=l,u=!1;function h(M,P,L,q,U){let X=!1;if(o){const K=x(q,L,P);c!==K&&(c=K,p(c.object)),X=g(M,q,L,U),X&&v(M,q,L,U)}else{const K=P.wireframe===!0;(c.geometry!==q.id||c.program!==L.id||c.wireframe!==K)&&(c.geometry=q.id,c.program=L.id,c.wireframe=K,X=!0)}U!==null&&t.update(U,n.ELEMENT_ARRAY_BUFFER),(X||u)&&(u=!1,E(M,P,L,q),U!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t.get(U).buffer))}function d(){return s.isWebGL2?n.createVertexArray():i.createVertexArrayOES()}function p(M){return s.isWebGL2?n.bindVertexArray(M):i.bindVertexArrayOES(M)}function f(M){return s.isWebGL2?n.deleteVertexArray(M):i.deleteVertexArrayOES(M)}function x(M,P,L){const q=L.wireframe===!0;let U=a[M.id];U===void 0&&(U={},a[M.id]=U);let X=U[P.id];X===void 0&&(X={},U[P.id]=X);let K=X[q];return K===void 0&&(K=m(d()),X[q]=K),K}function m(M){const P=[],L=[],q=[];for(let U=0;U=0){const j=U[ae];let ne=X[ae];if(ne===void 0&&(ae==="instanceMatrix"&&M.instanceMatrix&&(ne=M.instanceMatrix),ae==="instanceColor"&&M.instanceColor&&(ne=M.instanceColor)),j===void 0||j.attribute!==ne||ne&&j.data!==ne.data)return!0;K++}return c.attributesNum!==K||c.index!==q}function v(M,P,L,q){const U={},X=P.attributes;let K=0;const J=L.getAttributes();for(const ae in J)if(J[ae].location>=0){let j=X[ae];j===void 0&&(ae==="instanceMatrix"&&M.instanceMatrix&&(j=M.instanceMatrix),ae==="instanceColor"&&M.instanceColor&&(j=M.instanceColor));const ne={};ne.attribute=j,j&&j.data&&(ne.data=j.data),U[ae]=ne,K++}c.attributes=U,c.attributesNum=K,c.index=q}function b(){const M=c.newAttributes;for(let P=0,L=M.length;P=0){let he=U[J];if(he===void 0&&(J==="instanceMatrix"&&M.instanceMatrix&&(he=M.instanceMatrix),J==="instanceColor"&&M.instanceColor&&(he=M.instanceColor)),he!==void 0){const j=he.normalized,ne=he.itemSize,ge=t.get(he);if(ge===void 0)continue;const be=ge.buffer,Te=ge.type,ve=ge.bytesPerElement,Ge=s.isWebGL2===!0&&(Te===n.INT||Te===n.UNSIGNED_INT||he.gpuType===Bk);if(he.isInterleavedBufferAttribute){const $e=he.data,te=$e.stride,mt=he.offset;if($e.isInstancedInterleavedBuffer){for(let Ve=0;Ve0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";T="mediump"}return T==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}const o=typeof WebGL2RenderingContext<"u"&&n.constructor.name==="WebGL2RenderingContext";let a=t.precision!==void 0?t.precision:"highp";const l=i(a);l!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",l,"instead."),a=l);const c=o||e.has("WEBGL_draw_buffers"),u=t.logarithmicDepthBuffer===!0,h=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),d=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),p=n.getParameter(n.MAX_TEXTURE_SIZE),f=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),x=n.getParameter(n.MAX_VERTEX_ATTRIBS),m=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),g=n.getParameter(n.MAX_VARYING_VECTORS),v=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),b=d>0,y=o||e.has("OES_texture_float"),w=b&&y,C=o?n.getParameter(n.MAX_SAMPLES):0;return{isWebGL2:o,drawBuffers:c,getMaxAnisotropy:r,getMaxPrecision:i,precision:a,logarithmicDepthBuffer:u,maxTextures:h,maxVertexTextures:d,maxTextureSize:p,maxCubemapSize:f,maxAttributes:x,maxVertexUniforms:m,maxVaryings:g,maxFragmentUniforms:v,vertexTextures:b,floatFragmentTextures:y,floatVertexTextures:w,maxSamples:C}}function xfe(n){const e=this;let t=null,s=0,r=!1,i=!1;const o=new Ha,a=new Vt,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(h,d){const p=h.length!==0||d||s!==0||r;return r=d,s=h.length,p},this.beginShadows=function(){i=!0,u(null)},this.endShadows=function(){i=!1},this.setGlobalState=function(h,d){t=u(h,d,0)},this.setState=function(h,d,p){const f=h.clippingPlanes,x=h.clipIntersection,m=h.clipShadows,g=n.get(h);if(!r||f===null||f.length===0||i&&!m)i?u(null):c();else{const v=i?0:s,b=v*4;let y=g.clippingState||null;l.value=y,y=u(f,d,b,p);for(let w=0;w!==b;++w)y[w]=t[w];g.clippingState=y,this.numIntersection=x?this.numPlanes:0,this.numPlanes+=v}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=s>0),e.numPlanes=s,e.numIntersection=0}function u(h,d,p,f){const x=h!==null?h.length:0;let m=null;if(x!==0){if(m=l.value,f!==!0||m===null){const g=p+x*4,v=d.matrixWorldInverse;a.getNormalMatrix(v),(m===null||m.length0){const c=new Rhe(l.height);return c.fromEquirectangularTexture(n,o),e.set(o,c),o.addEventListener("dispose",r),t(c.texture,o.mapping)}else return null}}return o}function r(o){const a=o.target;a.removeEventListener("dispose",r);const l=e.get(a);l!==void 0&&(e.delete(a),l.dispose())}function i(){e=new WeakMap}return{get:s,dispose:i}}class lA extends rA{constructor(e=-1,t=1,s=1,r=-1,i=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=s,this.bottom=r,this.near=i,this.far=o,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,s,r,i,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=s,this.view.offsetY=r,this.view.width=i,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),s=(this.right+this.left)/2,r=(this.top+this.bottom)/2;let i=s-e,o=s+e,a=r+t,l=r-t;if(this.view!==null&&this.view.enabled){const c=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;i+=c*this.view.offsetX,o=i+c*this.view.width,a-=u*this.view.offsetY,l=a-u*this.view.height}this.projectionMatrix.makeOrthographic(i,o,a,l,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}const vc=4,U3=[.125,.215,.35,.446,.526,.582],Ja=20,x1=new lA,V3=new un;let v1=null,b1=0,y1=0;const qa=(1+Math.sqrt(5))/2,dc=1/qa,W3=[new fe(1,1,1),new fe(-1,1,1),new fe(1,1,-1),new fe(-1,1,-1),new fe(0,qa,dc),new fe(0,qa,-dc),new fe(dc,0,qa),new fe(-dc,0,qa),new fe(qa,dc,0),new fe(-qa,dc,0)];class G3{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,s=.1,r=100){v1=this._renderer.getRenderTarget(),b1=this._renderer.getActiveCubeFace(),y1=this._renderer.getActiveMipmapLevel(),this._setSize(256);const i=this._allocateTargets();return i.depthBuffer=!0,this._sceneToCubeUV(e,s,r,i),t>0&&this._blur(i,0,0,t),this._applyPMREM(i),this._cleanup(i),i}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=X3(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=q3(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?b:0,b,b),u.setRenderTarget(r),x&&u.render(f,a),u.render(e,a)}f.geometry.dispose(),f.material.dispose(),u.toneMapping=d,u.autoClear=h,e.background=m}_textureToCubeUV(e,t){const s=this._renderer,r=e.mapping===Uc||e.mapping===Vc;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=X3()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=q3());const i=r?this._cubemapMaterial:this._equirectMaterial,o=new Qn(this._lodPlanes[0],i),a=i.uniforms;a.envMap.value=e;const l=this._cubeSize;df(t,0,0,3*l,2*l),s.setRenderTarget(t),s.render(o,x1)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;for(let r=1;rJa&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Ja}`);const g=[];let v=0;for(let T=0;Tb-vc?r-b+vc:0),C=4*(this._cubeSize-y);df(t,w,C,3*y,2*y),l.setRenderTarget(t),l.render(h,x1)}}function bfe(n){const e=[],t=[],s=[];let r=n;const i=n-vc+1+U3.length;for(let o=0;on-vc?l=U3[o-n+vc-1]:o===0&&(l=0),s.push(l);const c=1/(a-2),u=-c,h=1+c,d=[u,u,h,u,h,h,u,u,h,h,u,h],p=6,f=6,x=3,m=2,g=1,v=new Float32Array(x*f*p),b=new Float32Array(m*f*p),y=new Float32Array(g*f*p);for(let C=0;C2?0:-1,R=[T,E,0,T+2/3,E,0,T+2/3,E+1,0,T,E,0,T+2/3,E+1,0,T,E+1,0];v.set(R,x*f*C),b.set(d,m*f*C);const _=[C,C,C,C,C,C];y.set(_,g*f*C)}const w=new Ra;w.setAttribute("position",new Xi(v,x)),w.setAttribute("uv",new Xi(b,m)),w.setAttribute("faceIndex",new Xi(y,g)),e.push(w),r>vc&&r--}return{lodPlanes:e,sizeLods:t,sigmas:s}}function H3(n,e,t){const s=new Tl(n,e,t);return s.texture.mapping=rg,s.texture.name="PMREM.cubeUv",s.scissorTest=!0,s}function df(n,e,t,s,r){n.viewport.set(e,t,s,r),n.scissor.set(e,t,s,r)}function yfe(n,e,t){const s=new Float32Array(Ja),r=new fe(0,1,0);return new fa({name:"SphericalGaussianBlur",defines:{n:Ja,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:s},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:db(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `,blending:sa,depthTest:!1,depthWrite:!1})}function q3(){return new fa({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:db(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `,blending:sa,depthTest:!1,depthWrite:!1})}function X3(){return new fa({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:db(),fragmentShader:` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `,blending:sa,depthTest:!1,depthWrite:!1})}function db(){return` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}function wfe(n){let e=new WeakMap,t=null;function s(a){if(a&&a.isTexture){const l=a.mapping,c=l===$x||l===Dx,u=l===Uc||l===Vc;if(c||u)if(a.isRenderTargetTexture&&a.needsPMREMUpdate===!0){a.needsPMREMUpdate=!1;let h=e.get(a);return t===null&&(t=new G3(n)),h=c?t.fromEquirectangular(a,h):t.fromCubemap(a,h),e.set(a,h),h.texture}else{if(e.has(a))return e.get(a).texture;{const h=a.image;if(c&&h&&h.height>0||u&&h&&r(h)){t===null&&(t=new G3(n));const d=c?t.fromEquirectangular(a):t.fromCubemap(a);return e.set(a,d),a.addEventListener("dispose",i),d.texture}else return null}}}return a}function r(a){let l=0;const c=6;for(let u=0;ue.maxTextureSize&&(k=Math.ceil(_/e.maxTextureSize),_=e.maxTextureSize);const F=new Float32Array(_*k*4*x),B=new Jk(F,_,k,x);B.type=yo,B.needsUpdate=!0;const M=R*4;for(let L=0;L0)return n;const r=e*t;let i=K3[r];if(i===void 0&&(i=new Float32Array(r),K3[r]=i),e!==0){s.toArray(i,0);for(let o=1,a=0;o!==e;++o)a+=t,n[o].toArray(i,a)}return i}function ps(n,e){if(n.length!==e.length)return!1;for(let t=0,s=n.length;t":" "} ${a}: ${t[o]}`)}return s.join(` +`)}function C0e(n){const e=cn.getPrimaries(cn.workingColorSpace),t=cn.getPrimaries(n);let s;switch(e===t?s="":e===u0&&t===c0?s="LinearDisplayP3ToLinearSRGB":e===c0&&t===u0&&(s="LinearSRGBToLinearDisplayP3"),n){case Ro:case ig:return[s,"LinearTransferOETF"];case Is:case cb:return[s,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",n),[s,"LinearTransferOETF"]}}function tS(n,e,t){const s=n.getShaderParameter(e,n.COMPILE_STATUS),r=n.getShaderInfoLog(e).trim();if(s&&r==="")return"";const i=/ERROR: 0:(\d+)/.exec(r);if(i){const o=parseInt(i[1]);return t.toUpperCase()+` + +`+r+` + +`+S0e(n.getShaderSource(e),o)}else return r}function _0e(n,e){const t=C0e(e);return`vec4 ${n}( vec4 value ) { return ${t[0]}( ${t[1]}( value ) ); }`}function T0e(n,e){let t;switch(e){case Pue:t="Linear";break;case Lue:t="Reinhard";break;case Fue:t="OptimizedCineon";break;case Oue:t="ACESFilmic";break;case Bue:t="AgX";break;case zue:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+n+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}function I0e(n){return[n.extensionDerivatives||n.envMapCubeUVHeight||n.bumpMap||n.normalMapTangentSpace||n.clearcoatNormalMap||n.flatShading||n.alphaToCoverage||n.shaderID==="physical"?"#extension GL_OES_standard_derivatives : enable":"",(n.extensionFragDepth||n.logarithmicDepthBuffer)&&n.rendererExtensionFragDepth?"#extension GL_EXT_frag_depth : enable":"",n.extensionDrawBuffers&&n.rendererExtensionDrawBuffers?"#extension GL_EXT_draw_buffers : require":"",(n.extensionShaderTextureLOD||n.envMap||n.transmission)&&n.rendererExtensionShaderTextureLod?"#extension GL_EXT_shader_texture_lod : enable":""].filter(bc).join(` +`)}function E0e(n){return[n.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",n.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(bc).join(` +`)}function k0e(n){const e=[];for(const t in n){const s=n[t];s!==!1&&e.push("#define "+t+" "+s)}return e.join(` +`)}function A0e(n,e){const t={},s=n.getProgramParameter(e,n.ACTIVE_ATTRIBUTES);for(let r=0;r/gm;function Bx(n){return n.replace(R0e,N0e)}const M0e=new Map([["encodings_fragment","colorspace_fragment"],["encodings_pars_fragment","colorspace_pars_fragment"],["output_fragment","opaque_fragment"]]);function N0e(n,e){let t=Ft[e];if(t===void 0){const s=M0e.get(e);if(s!==void 0)t=Ft[s],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,s);else throw new Error("Can not resolve #include <"+e+">")}return Bx(t)}const $0e=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function rS(n){return n.replace($0e,D0e)}function D0e(n,e,t,s){let r="";for(let i=parseInt(e);i0&&(g+=` +`),v=[p,"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,x].filter(bc).join(` +`),v.length>0&&(v+=` +`)):(g=[iS(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,x,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors&&t.isWebGL2?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0&&t.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",t.morphTargetsCount>0&&t.isWebGL2?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0&&t.isWebGL2?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.useLegacyLights?"#define LEGACY_LIGHTS":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.logarithmicDepthBuffer&&t.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )"," attribute vec3 morphTarget0;"," attribute vec3 morphTarget1;"," attribute vec3 morphTarget2;"," attribute vec3 morphTarget3;"," #ifdef USE_MORPHNORMALS"," attribute vec3 morphNormal0;"," attribute vec3 morphNormal1;"," attribute vec3 morphNormal2;"," attribute vec3 morphNormal3;"," #else"," attribute vec3 morphTarget4;"," attribute vec3 morphTarget5;"," attribute vec3 morphTarget6;"," attribute vec3 morphTarget7;"," #endif","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(bc).join(` +`),v=[p,iS(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,x,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+u:"",t.envMap?"#define "+h:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.useLegacyLights?"#define LEGACY_LIGHTS":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.logarithmicDepthBuffer&&t.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==ra?"#define TONE_MAPPING":"",t.toneMapping!==ra?Ft.tonemapping_pars_fragment:"",t.toneMapping!==ra?T0e("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",Ft.colorspace_pars_fragment,_0e("linearToOutputTexel",t.outputColorSpace),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` +`].filter(bc).join(` +`)),o=Bx(o),o=nS(o,t),o=sS(o,t),a=Bx(a),a=nS(a,t),a=sS(a,t),o=rS(o),a=rS(a),t.isWebGL2&&t.isRawShaderMaterial!==!0&&(b=`#version 300 es +`,g=[f,"precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join(` +`)+` +`+g,v=["precision mediump sampler2DArray;","#define varying in",t.glslVersion===w3?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===w3?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`)+` +`+v);const y=b+g+o,w=b+v+a,C=eS(r,r.VERTEX_SHADER,y),T=eS(r,r.FRAGMENT_SHADER,w);r.attachShader(m,C),r.attachShader(m,T),t.index0AttributeName!==void 0?r.bindAttribLocation(m,0,t.index0AttributeName):t.morphTargets===!0&&r.bindAttribLocation(m,0,"position"),r.linkProgram(m);function E(F){if(n.debug.checkShaderErrors){const B=r.getProgramInfoLog(m).trim(),M=r.getShaderInfoLog(C).trim(),P=r.getShaderInfoLog(T).trim();let L=!0,q=!0;if(r.getProgramParameter(m,r.LINK_STATUS)===!1)if(L=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(r,m,C,T);else{const U=tS(r,C,"vertex"),X=tS(r,T,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(m,r.VALIDATE_STATUS)+` + +Material Name: `+F.name+` +Material Type: `+F.type+` + +Program Info Log: `+B+` +`+U+` +`+X)}else B!==""?console.warn("THREE.WebGLProgram: Program Info Log:",B):(M===""||P==="")&&(q=!1);q&&(F.diagnostics={runnable:L,programLog:B,vertexShader:{log:M,prefix:g},fragmentShader:{log:P,prefix:v}})}r.deleteShader(C),r.deleteShader(T),R=new If(r,m),_=A0e(r,m)}let R;this.getUniforms=function(){return R===void 0&&E(this),R};let _;this.getAttributes=function(){return _===void 0&&E(this),_};let k=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return k===!1&&(k=r.getProgramParameter(m,y0e)),k},this.destroy=function(){s.releaseStatesOfProgram(this),r.deleteProgram(m),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=w0e++,this.cacheKey=e,this.usedTimes=1,this.program=m,this.vertexShader=C,this.fragmentShader=T,this}let U0e=0;class V0e{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,s=e.fragmentShader,r=this._getShaderStage(t),i=this._getShaderStage(s),o=this._getShaderCacheForMaterial(e);return o.has(r)===!1&&(o.add(r),r.usedTimes++),o.has(i)===!1&&(o.add(i),i.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const s of t)s.usedTimes--,s.usedTimes===0&&this.shaderCache.delete(s.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let s=t.get(e);return s===void 0&&(s=new Set,t.set(e,s)),s}_getShaderStage(e){const t=this.shaderCache;let s=t.get(e);return s===void 0&&(s=new W0e(e),t.set(e,s)),s}}class W0e{constructor(e){this.id=U0e++,this.code=e,this.usedTimes=0}}function G0e(n,e,t,s,r,i,o){const a=new Qk,l=new V0e,c=new Set,u=[],h=r.isWebGL2,d=r.logarithmicDepthBuffer,p=r.vertexTextures;let f=r.precision;const x={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function m(_){return c.add(_),_===0?"uv":`uv${_}`}function g(_,k,F,B,M){const P=B.fog,L=M.geometry,q=_.isMeshStandardMaterial?B.environment:null,U=(_.isMeshStandardMaterial?t:e).get(_.envMap||q),X=U&&U.mapping===rg?U.image.height:null,K=x[_.type];_.precision!==null&&(f=r.getMaxPrecision(_.precision),f!==_.precision&&console.warn("THREE.WebGLProgram.getParameters:",_.precision,"not supported, using",f,"instead."));const J=L.morphAttributes.position||L.morphAttributes.normal||L.morphAttributes.color,ae=J!==void 0?J.length:0;let he=0;L.morphAttributes.position!==void 0&&(he=1),L.morphAttributes.normal!==void 0&&(he=2),L.morphAttributes.color!==void 0&&(he=3);let j,ne,ge,be;if(K){const vn=Oi[K];j=vn.vertexShader,ne=vn.fragmentShader}else j=_.vertexShader,ne=_.fragmentShader,l.update(_),ge=l.getVertexShaderID(_),be=l.getFragmentShaderID(_);const Te=n.getRenderTarget(),ve=M.isInstancedMesh===!0,Ge=M.isBatchedMesh===!0,$e=!!_.map,te=!!_.matcap,mt=!!U,Ve=!!_.aoMap,Ke=!!_.lightMap,Pe=!!_.bumpMap,gt=!!_.normalMap,Je=!!_.displacementMap,z=!!_.emissiveMap,$=!!_.metalnessMap,ue=!!_.roughnessMap,Se=_.anisotropy>0,ye=_.clearcoat>0,Ce=_.iridescence>0,Ze=_.sheen>0,Fe=_.transmission>0,je=Se&&!!_.anisotropyMap,ot=ye&&!!_.clearcoatMap,xt=ye&&!!_.clearcoatNormalMap,Ie=ye&&!!_.clearcoatRoughnessMap,Zt=Ce&&!!_.iridescenceMap,zt=Ce&&!!_.iridescenceThicknessMap,wt=Ze&&!!_.sheenColorMap,ht=Ze&&!!_.sheenRoughnessMap,rt=!!_.specularMap,Pt=!!_.specularColorMap,rn=!!_.specularIntensityMap,_n=Fe&&!!_.transmissionMap,Gt=Fe&&!!_.thicknessMap,dn=!!_.gradientMap,W=!!_.alphaMap,Oe=_.alphaTest>0,ze=!!_.alphaHash,at=!!_.extensions;let vt=ra;_.toneMapped&&(Te===null||Te.isXRRenderTarget===!0)&&(vt=n.toneMapping);const on={isWebGL2:h,shaderID:K,shaderType:_.type,shaderName:_.name,vertexShader:j,fragmentShader:ne,defines:_.defines,customVertexShaderID:ge,customFragmentShaderID:be,isRawShaderMaterial:_.isRawShaderMaterial===!0,glslVersion:_.glslVersion,precision:f,batching:Ge,instancing:ve,instancingColor:ve&&M.instanceColor!==null,supportsVertexTextures:p,outputColorSpace:Te===null?n.outputColorSpace:Te.isXRRenderTarget===!0?Te.texture.colorSpace:Ro,alphaToCoverage:!!_.alphaToCoverage,map:$e,matcap:te,envMap:mt,envMapMode:mt&&U.mapping,envMapCubeUVHeight:X,aoMap:Ve,lightMap:Ke,bumpMap:Pe,normalMap:gt,displacementMap:p&&Je,emissiveMap:z,normalMapObjectSpace:gt&&_.normalMapType===Jue,normalMapTangentSpace:gt&&_.normalMapType===Zue,metalnessMap:$,roughnessMap:ue,anisotropy:Se,anisotropyMap:je,clearcoat:ye,clearcoatMap:ot,clearcoatNormalMap:xt,clearcoatRoughnessMap:Ie,iridescence:Ce,iridescenceMap:Zt,iridescenceThicknessMap:zt,sheen:Ze,sheenColorMap:wt,sheenRoughnessMap:ht,specularMap:rt,specularColorMap:Pt,specularIntensityMap:rn,transmission:Fe,transmissionMap:_n,thicknessMap:Gt,gradientMap:dn,opaque:_.transparent===!1&&_.blending===_c&&_.alphaToCoverage===!1,alphaMap:W,alphaTest:Oe,alphaHash:ze,combine:_.combine,mapUv:$e&&m(_.map.channel),aoMapUv:Ve&&m(_.aoMap.channel),lightMapUv:Ke&&m(_.lightMap.channel),bumpMapUv:Pe&&m(_.bumpMap.channel),normalMapUv:gt&&m(_.normalMap.channel),displacementMapUv:Je&&m(_.displacementMap.channel),emissiveMapUv:z&&m(_.emissiveMap.channel),metalnessMapUv:$&&m(_.metalnessMap.channel),roughnessMapUv:ue&&m(_.roughnessMap.channel),anisotropyMapUv:je&&m(_.anisotropyMap.channel),clearcoatMapUv:ot&&m(_.clearcoatMap.channel),clearcoatNormalMapUv:xt&&m(_.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ie&&m(_.clearcoatRoughnessMap.channel),iridescenceMapUv:Zt&&m(_.iridescenceMap.channel),iridescenceThicknessMapUv:zt&&m(_.iridescenceThicknessMap.channel),sheenColorMapUv:wt&&m(_.sheenColorMap.channel),sheenRoughnessMapUv:ht&&m(_.sheenRoughnessMap.channel),specularMapUv:rt&&m(_.specularMap.channel),specularColorMapUv:Pt&&m(_.specularColorMap.channel),specularIntensityMapUv:rn&&m(_.specularIntensityMap.channel),transmissionMapUv:_n&&m(_.transmissionMap.channel),thicknessMapUv:Gt&&m(_.thicknessMap.channel),alphaMapUv:W&&m(_.alphaMap.channel),vertexTangents:!!L.attributes.tangent&&(gt||Se),vertexColors:_.vertexColors,vertexAlphas:_.vertexColors===!0&&!!L.attributes.color&&L.attributes.color.itemSize===4,pointsUvs:M.isPoints===!0&&!!L.attributes.uv&&($e||W),fog:!!P,useFog:_.fog===!0,fogExp2:!!P&&P.isFogExp2,flatShading:_.flatShading===!0,sizeAttenuation:_.sizeAttenuation===!0,logarithmicDepthBuffer:d,skinning:M.isSkinnedMesh===!0,morphTargets:L.morphAttributes.position!==void 0,morphNormals:L.morphAttributes.normal!==void 0,morphColors:L.morphAttributes.color!==void 0,morphTargetsCount:ae,morphTextureStride:he,numDirLights:k.directional.length,numPointLights:k.point.length,numSpotLights:k.spot.length,numSpotLightMaps:k.spotLightMap.length,numRectAreaLights:k.rectArea.length,numHemiLights:k.hemi.length,numDirLightShadows:k.directionalShadowMap.length,numPointLightShadows:k.pointShadowMap.length,numSpotLightShadows:k.spotShadowMap.length,numSpotLightShadowsWithMaps:k.numSpotLightShadowsWithMaps,numLightProbes:k.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:_.dithering,shadowMapEnabled:n.shadowMap.enabled&&F.length>0,shadowMapType:n.shadowMap.type,toneMapping:vt,useLegacyLights:n._useLegacyLights,decodeVideoTexture:$e&&_.map.isVideoTexture===!0&&cn.getTransfer(_.map.colorSpace)===Tn,premultipliedAlpha:_.premultipliedAlpha,doubleSided:_.side===Bi,flipSided:_.side===mr,useDepthPacking:_.depthPacking>=0,depthPacking:_.depthPacking||0,index0AttributeName:_.index0AttributeName,extensionDerivatives:at&&_.extensions.derivatives===!0,extensionFragDepth:at&&_.extensions.fragDepth===!0,extensionDrawBuffers:at&&_.extensions.drawBuffers===!0,extensionShaderTextureLOD:at&&_.extensions.shaderTextureLOD===!0,extensionClipCullDistance:at&&_.extensions.clipCullDistance===!0&&s.has("WEBGL_clip_cull_distance"),extensionMultiDraw:at&&_.extensions.multiDraw===!0&&s.has("WEBGL_multi_draw"),rendererExtensionFragDepth:h||s.has("EXT_frag_depth"),rendererExtensionDrawBuffers:h||s.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:h||s.has("EXT_shader_texture_lod"),rendererExtensionParallelShaderCompile:s.has("KHR_parallel_shader_compile"),customProgramCacheKey:_.customProgramCacheKey()};return on.vertexUv1s=c.has(1),on.vertexUv2s=c.has(2),on.vertexUv3s=c.has(3),c.clear(),on}function v(_){const k=[];if(_.shaderID?k.push(_.shaderID):(k.push(_.customVertexShaderID),k.push(_.customFragmentShaderID)),_.defines!==void 0)for(const F in _.defines)k.push(F),k.push(_.defines[F]);return _.isRawShaderMaterial===!1&&(b(k,_),y(k,_),k.push(n.outputColorSpace)),k.push(_.customProgramCacheKey),k.join()}function b(_,k){_.push(k.precision),_.push(k.outputColorSpace),_.push(k.envMapMode),_.push(k.envMapCubeUVHeight),_.push(k.mapUv),_.push(k.alphaMapUv),_.push(k.lightMapUv),_.push(k.aoMapUv),_.push(k.bumpMapUv),_.push(k.normalMapUv),_.push(k.displacementMapUv),_.push(k.emissiveMapUv),_.push(k.metalnessMapUv),_.push(k.roughnessMapUv),_.push(k.anisotropyMapUv),_.push(k.clearcoatMapUv),_.push(k.clearcoatNormalMapUv),_.push(k.clearcoatRoughnessMapUv),_.push(k.iridescenceMapUv),_.push(k.iridescenceThicknessMapUv),_.push(k.sheenColorMapUv),_.push(k.sheenRoughnessMapUv),_.push(k.specularMapUv),_.push(k.specularColorMapUv),_.push(k.specularIntensityMapUv),_.push(k.transmissionMapUv),_.push(k.thicknessMapUv),_.push(k.combine),_.push(k.fogExp2),_.push(k.sizeAttenuation),_.push(k.morphTargetsCount),_.push(k.morphAttributeCount),_.push(k.numDirLights),_.push(k.numPointLights),_.push(k.numSpotLights),_.push(k.numSpotLightMaps),_.push(k.numHemiLights),_.push(k.numRectAreaLights),_.push(k.numDirLightShadows),_.push(k.numPointLightShadows),_.push(k.numSpotLightShadows),_.push(k.numSpotLightShadowsWithMaps),_.push(k.numLightProbes),_.push(k.shadowMapType),_.push(k.toneMapping),_.push(k.numClippingPlanes),_.push(k.numClipIntersection),_.push(k.depthPacking)}function y(_,k){a.disableAll(),k.isWebGL2&&a.enable(0),k.supportsVertexTextures&&a.enable(1),k.instancing&&a.enable(2),k.instancingColor&&a.enable(3),k.matcap&&a.enable(4),k.envMap&&a.enable(5),k.normalMapObjectSpace&&a.enable(6),k.normalMapTangentSpace&&a.enable(7),k.clearcoat&&a.enable(8),k.iridescence&&a.enable(9),k.alphaTest&&a.enable(10),k.vertexColors&&a.enable(11),k.vertexAlphas&&a.enable(12),k.vertexUv1s&&a.enable(13),k.vertexUv2s&&a.enable(14),k.vertexUv3s&&a.enable(15),k.vertexTangents&&a.enable(16),k.anisotropy&&a.enable(17),k.alphaHash&&a.enable(18),k.batching&&a.enable(19),_.push(a.mask),a.disableAll(),k.fog&&a.enable(0),k.useFog&&a.enable(1),k.flatShading&&a.enable(2),k.logarithmicDepthBuffer&&a.enable(3),k.skinning&&a.enable(4),k.morphTargets&&a.enable(5),k.morphNormals&&a.enable(6),k.morphColors&&a.enable(7),k.premultipliedAlpha&&a.enable(8),k.shadowMapEnabled&&a.enable(9),k.useLegacyLights&&a.enable(10),k.doubleSided&&a.enable(11),k.flipSided&&a.enable(12),k.useDepthPacking&&a.enable(13),k.dithering&&a.enable(14),k.transmission&&a.enable(15),k.sheen&&a.enable(16),k.opaque&&a.enable(17),k.pointsUvs&&a.enable(18),k.decodeVideoTexture&&a.enable(19),k.alphaToCoverage&&a.enable(20),_.push(a.mask)}function w(_){const k=x[_.type];let F;if(k){const B=Oi[k];F=Ihe.clone(B.uniforms)}else F=_.uniforms;return F}function C(_,k){let F;for(let B=0,M=u.length;B0?s.push(g):p.transparent===!0?r.push(g):t.push(g)}function l(h,d,p,f,x,m){const g=o(h,d,p,f,x,m);p.transmission>0?s.unshift(g):p.transparent===!0?r.unshift(g):t.unshift(g)}function c(h,d){t.length>1&&t.sort(h||q0e),s.length>1&&s.sort(d||oS),r.length>1&&r.sort(d||oS)}function u(){for(let h=e,d=n.length;h=i.length?(o=new aS,i.push(o)):o=i[r],o}function t(){n=new WeakMap}return{get:e,dispose:t}}function K0e(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new fe,color:new un};break;case"SpotLight":t={position:new fe,direction:new fe,color:new un,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new fe,color:new un,distance:0,decay:0};break;case"HemisphereLight":t={direction:new fe,skyColor:new un,groundColor:new un};break;case"RectAreaLight":t={color:new un,position:new fe,halfWidth:new fe,halfHeight:new fe};break}return n[e.id]=t,t}}}function j0e(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new en};break;case"SpotLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new en};break;case"PointLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new en,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let Y0e=0;function Z0e(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function J0e(n,e){const t=new K0e,s=j0e(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let u=0;u<9;u++)r.probe.push(new fe);const i=new fe,o=new ks,a=new ks;function l(u,h){let d=0,p=0,f=0;for(let F=0;F<9;F++)r.probe[F].set(0,0,0);let x=0,m=0,g=0,v=0,b=0,y=0,w=0,C=0,T=0,E=0,R=0;u.sort(Z0e);const _=h===!0?Math.PI:1;for(let F=0,B=u.length;F0&&(e.isWebGL2?n.has("OES_texture_float_linear")===!0?(r.rectAreaLTC1=We.LTC_FLOAT_1,r.rectAreaLTC2=We.LTC_FLOAT_2):(r.rectAreaLTC1=We.LTC_HALF_1,r.rectAreaLTC2=We.LTC_HALF_2):n.has("OES_texture_float_linear")===!0?(r.rectAreaLTC1=We.LTC_FLOAT_1,r.rectAreaLTC2=We.LTC_FLOAT_2):n.has("OES_texture_half_float_linear")===!0?(r.rectAreaLTC1=We.LTC_HALF_1,r.rectAreaLTC2=We.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),r.ambient[0]=d,r.ambient[1]=p,r.ambient[2]=f;const k=r.hash;(k.directionalLength!==x||k.pointLength!==m||k.spotLength!==g||k.rectAreaLength!==v||k.hemiLength!==b||k.numDirectionalShadows!==y||k.numPointShadows!==w||k.numSpotShadows!==C||k.numSpotMaps!==T||k.numLightProbes!==R)&&(r.directional.length=x,r.spot.length=g,r.rectArea.length=v,r.point.length=m,r.hemi.length=b,r.directionalShadow.length=y,r.directionalShadowMap.length=y,r.pointShadow.length=w,r.pointShadowMap.length=w,r.spotShadow.length=C,r.spotShadowMap.length=C,r.directionalShadowMatrix.length=y,r.pointShadowMatrix.length=w,r.spotLightMatrix.length=C+T-E,r.spotLightMap.length=T,r.numSpotLightShadowsWithMaps=E,r.numLightProbes=R,k.directionalLength=x,k.pointLength=m,k.spotLength=g,k.rectAreaLength=v,k.hemiLength=b,k.numDirectionalShadows=y,k.numPointShadows=w,k.numSpotShadows=C,k.numSpotMaps=T,k.numLightProbes=R,r.version=Y0e++)}function c(u,h){let d=0,p=0,f=0,x=0,m=0;const g=h.matrixWorldInverse;for(let v=0,b=u.length;v=a.length?(l=new lS(n,e),a.push(l)):l=a[o],l}function r(){t=new WeakMap}return{get:s,dispose:r}}class eme extends ag{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=jue,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class tme extends ag{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}const nme=`void main() { + gl_Position = vec4( position, 1.0 ); +}`,sme=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`;function rme(n,e,t){let s=new oA;const r=new en,i=new en,o=new Es,a=new eme({depthPacking:Yue}),l=new tme,c={},u=t.maxTextureSize,h={[pa]:mr,[mr]:pa,[Bi]:Bi},d=new fa({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new en},radius:{value:4}},vertexShader:nme,fragmentShader:sme}),p=d.clone();p.defines.HORIZONTAL_PASS=1;const f=new Ra;f.setAttribute("position",new Xi(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const x=new Qn(f,d),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Fk;let g=this.type;this.render=function(C,T,E){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||C.length===0)return;const R=n.getRenderTarget(),_=n.getActiveCubeFace(),k=n.getActiveMipmapLevel(),F=n.state;F.setBlending(sa),F.buffers.color.setClear(1,1,1,1),F.buffers.depth.setTest(!0),F.setScissorTest(!1);const B=g!==go&&this.type===go,M=g===go&&this.type!==go;for(let P=0,L=C.length;Pu||r.y>u)&&(r.x>u&&(i.x=Math.floor(u/X.x),r.x=i.x*X.x,U.mapSize.x=i.x),r.y>u&&(i.y=Math.floor(u/X.y),r.y=i.y*X.y,U.mapSize.y=i.y)),U.map===null||B===!0||M===!0){const J=this.type!==go?{minFilter:Xs,magFilter:Xs}:{};U.map!==null&&U.map.dispose(),U.map=new Tl(r.x,r.y,J),U.map.texture.name=q.name+".shadowMap",U.camera.updateProjectionMatrix()}n.setRenderTarget(U.map),n.clear();const K=U.getViewportCount();for(let J=0;J0||T.map&&T.alphaTest>0){const F=_.uuid,B=T.uuid;let M=c[F];M===void 0&&(M={},c[F]=M);let P=M[B];P===void 0&&(P=_.clone(),M[B]=P,T.addEventListener("dispose",w)),_=P}if(_.visible=T.visible,_.wireframe=T.wireframe,R===go?_.side=T.shadowSide!==null?T.shadowSide:T.side:_.side=T.shadowSide!==null?T.shadowSide:h[T.side],_.alphaMap=T.alphaMap,_.alphaTest=T.alphaTest,_.map=T.map,_.clipShadows=T.clipShadows,_.clippingPlanes=T.clippingPlanes,_.clipIntersection=T.clipIntersection,_.displacementMap=T.displacementMap,_.displacementScale=T.displacementScale,_.displacementBias=T.displacementBias,_.wireframeLinewidth=T.wireframeLinewidth,_.linewidth=T.linewidth,E.isPointLight===!0&&_.isMeshDistanceMaterial===!0){const F=n.properties.get(_);F.light=E}return _}function y(C,T,E,R,_){if(C.visible===!1)return;if(C.layers.test(T.layers)&&(C.isMesh||C.isLine||C.isPoints)&&(C.castShadow||C.receiveShadow&&_===go)&&(!C.frustumCulled||s.intersectsObject(C))){C.modelViewMatrix.multiplyMatrices(E.matrixWorldInverse,C.matrixWorld);const B=e.update(C),M=C.material;if(Array.isArray(M)){const P=B.groups;for(let L=0,q=P.length;L=1):K.indexOf("OpenGL ES")!==-1&&(X=parseFloat(/^OpenGL ES (\d)/.exec(K)[1]),U=X>=2);let J=null,ae={};const he=n.getParameter(n.SCISSOR_BOX),j=n.getParameter(n.VIEWPORT),ne=new Es().fromArray(he),ge=new Es().fromArray(j);function be(W,Oe,ze,at){const vt=new Uint8Array(4),on=n.createTexture();n.bindTexture(W,on),n.texParameteri(W,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(W,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let vn=0;vn"u"?!1:/OculusBrowser/g.test(navigator.userAgent),u=new WeakMap;let h;const d=new WeakMap;let p=!1;try{p=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function f(z,$){return p?new OffscreenCanvas(z,$):d0("canvas")}function x(z,$,ue,Se){let ye=1;if((z.width>Se||z.height>Se)&&(ye=Se/Math.max(z.width,z.height)),ye<1||$===!0)if(typeof HTMLImageElement<"u"&&z instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&z instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&z instanceof ImageBitmap){const Ce=$?zx:Math.floor,Ze=Ce(ye*z.width),Fe=Ce(ye*z.height);h===void 0&&(h=f(Ze,Fe));const je=ue?f(Ze,Fe):h;return je.width=Ze,je.height=Fe,je.getContext("2d").drawImage(z,0,0,Ze,Fe),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+z.width+"x"+z.height+") to ("+Ze+"x"+Fe+")."),je}else return"data"in z&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+z.width+"x"+z.height+")."),z;return z}function m(z){return S3(z.width)&&S3(z.height)}function g(z){return a?!1:z.wrapS!==fi||z.wrapT!==fi||z.minFilter!==Xs&&z.minFilter!==ur}function v(z,$){return z.generateMipmaps&&$&&z.minFilter!==Xs&&z.minFilter!==ur}function b(z){n.generateMipmap(z)}function y(z,$,ue,Se,ye=!1){if(a===!1)return $;if(z!==null){if(n[z]!==void 0)return n[z];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+z+"'")}let Ce=$;if($===n.RED&&(ue===n.FLOAT&&(Ce=n.R32F),ue===n.HALF_FLOAT&&(Ce=n.R16F),ue===n.UNSIGNED_BYTE&&(Ce=n.R8)),$===n.RED_INTEGER&&(ue===n.UNSIGNED_BYTE&&(Ce=n.R8UI),ue===n.UNSIGNED_SHORT&&(Ce=n.R16UI),ue===n.UNSIGNED_INT&&(Ce=n.R32UI),ue===n.BYTE&&(Ce=n.R8I),ue===n.SHORT&&(Ce=n.R16I),ue===n.INT&&(Ce=n.R32I)),$===n.RG&&(ue===n.FLOAT&&(Ce=n.RG32F),ue===n.HALF_FLOAT&&(Ce=n.RG16F),ue===n.UNSIGNED_BYTE&&(Ce=n.RG8)),$===n.RGBA){const Ze=ye?l0:cn.getTransfer(Se);ue===n.FLOAT&&(Ce=n.RGBA32F),ue===n.HALF_FLOAT&&(Ce=n.RGBA16F),ue===n.UNSIGNED_BYTE&&(Ce=Ze===Tn?n.SRGB8_ALPHA8:n.RGBA8),ue===n.UNSIGNED_SHORT_4_4_4_4&&(Ce=n.RGBA4),ue===n.UNSIGNED_SHORT_5_5_5_1&&(Ce=n.RGB5_A1)}return(Ce===n.R16F||Ce===n.R32F||Ce===n.RG16F||Ce===n.RG32F||Ce===n.RGBA16F||Ce===n.RGBA32F)&&e.get("EXT_color_buffer_float"),Ce}function w(z,$,ue){return v(z,ue)===!0||z.isFramebufferTexture&&z.minFilter!==Xs&&z.minFilter!==ur?Math.log2(Math.max($.width,$.height))+1:z.mipmaps!==void 0&&z.mipmaps.length>0?z.mipmaps.length:z.isCompressedTexture&&Array.isArray(z.image)?$.mipmaps.length:1}function C(z){return z===Xs||z===Xw||z===xh?n.NEAREST:n.LINEAR}function T(z){const $=z.target;$.removeEventListener("dispose",T),R($),$.isVideoTexture&&u.delete($)}function E(z){const $=z.target;$.removeEventListener("dispose",E),k($)}function R(z){const $=s.get(z);if($.__webglInit===void 0)return;const ue=z.source,Se=d.get(ue);if(Se){const ye=Se[$.__cacheKey];ye.usedTimes--,ye.usedTimes===0&&_(z),Object.keys(Se).length===0&&d.delete(ue)}s.remove(z)}function _(z){const $=s.get(z);n.deleteTexture($.__webglTexture);const ue=z.source,Se=d.get(ue);delete Se[$.__cacheKey],o.memory.textures--}function k(z){const $=z.texture,ue=s.get(z),Se=s.get($);if(Se.__webglTexture!==void 0&&(n.deleteTexture(Se.__webglTexture),o.memory.textures--),z.depthTexture&&z.depthTexture.dispose(),z.isWebGLCubeRenderTarget)for(let ye=0;ye<6;ye++){if(Array.isArray(ue.__webglFramebuffer[ye]))for(let Ce=0;Ce=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+z+" texture units while this GPU supports only "+r.maxTextures),F+=1,z}function P(z){const $=[];return $.push(z.wrapS),$.push(z.wrapT),$.push(z.wrapR||0),$.push(z.magFilter),$.push(z.minFilter),$.push(z.anisotropy),$.push(z.internalFormat),$.push(z.format),$.push(z.type),$.push(z.generateMipmaps),$.push(z.premultiplyAlpha),$.push(z.flipY),$.push(z.unpackAlignment),$.push(z.colorSpace),$.join()}function L(z,$){const ue=s.get(z);if(z.isVideoTexture&>(z),z.isRenderTargetTexture===!1&&z.version>0&&ue.__version!==z.version){const Se=z.image;if(Se===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(Se.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{ne(ue,z,$);return}}t.bindTexture(n.TEXTURE_2D,ue.__webglTexture,n.TEXTURE0+$)}function q(z,$){const ue=s.get(z);if(z.version>0&&ue.__version!==z.version){ne(ue,z,$);return}t.bindTexture(n.TEXTURE_2D_ARRAY,ue.__webglTexture,n.TEXTURE0+$)}function U(z,$){const ue=s.get(z);if(z.version>0&&ue.__version!==z.version){ne(ue,z,$);return}t.bindTexture(n.TEXTURE_3D,ue.__webglTexture,n.TEXTURE0+$)}function X(z,$){const ue=s.get(z);if(z.version>0&&ue.__version!==z.version){ge(ue,z,$);return}t.bindTexture(n.TEXTURE_CUBE_MAP,ue.__webglTexture,n.TEXTURE0+$)}const K={[Px]:n.REPEAT,[fi]:n.CLAMP_TO_EDGE,[Lx]:n.MIRRORED_REPEAT},J={[Xs]:n.NEAREST,[Xw]:n.NEAREST_MIPMAP_NEAREST,[xh]:n.NEAREST_MIPMAP_LINEAR,[ur]:n.LINEAR,[qg]:n.LINEAR_MIPMAP_NEAREST,[sl]:n.LINEAR_MIPMAP_LINEAR},ae={[Que]:n.NEVER,[ihe]:n.ALWAYS,[ehe]:n.LESS,[Kk]:n.LEQUAL,[the]:n.EQUAL,[rhe]:n.GEQUAL,[nhe]:n.GREATER,[she]:n.NOTEQUAL};function he(z,$,ue){if($.type===yo&&e.has("OES_texture_float_linear")===!1&&($.magFilter===ur||$.magFilter===qg||$.magFilter===xh||$.magFilter===sl||$.minFilter===ur||$.minFilter===qg||$.minFilter===xh||$.minFilter===sl)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),ue?(n.texParameteri(z,n.TEXTURE_WRAP_S,K[$.wrapS]),n.texParameteri(z,n.TEXTURE_WRAP_T,K[$.wrapT]),(z===n.TEXTURE_3D||z===n.TEXTURE_2D_ARRAY)&&n.texParameteri(z,n.TEXTURE_WRAP_R,K[$.wrapR]),n.texParameteri(z,n.TEXTURE_MAG_FILTER,J[$.magFilter]),n.texParameteri(z,n.TEXTURE_MIN_FILTER,J[$.minFilter])):(n.texParameteri(z,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(z,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),(z===n.TEXTURE_3D||z===n.TEXTURE_2D_ARRAY)&&n.texParameteri(z,n.TEXTURE_WRAP_R,n.CLAMP_TO_EDGE),($.wrapS!==fi||$.wrapT!==fi)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),n.texParameteri(z,n.TEXTURE_MAG_FILTER,C($.magFilter)),n.texParameteri(z,n.TEXTURE_MIN_FILTER,C($.minFilter)),$.minFilter!==Xs&&$.minFilter!==ur&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),$.compareFunction&&(n.texParameteri(z,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(z,n.TEXTURE_COMPARE_FUNC,ae[$.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){const Se=e.get("EXT_texture_filter_anisotropic");if($.magFilter===Xs||$.minFilter!==xh&&$.minFilter!==sl||$.type===yo&&e.has("OES_texture_float_linear")===!1||a===!1&&$.type===Jh&&e.has("OES_texture_half_float_linear")===!1)return;($.anisotropy>1||s.get($).__currentAnisotropy)&&(n.texParameterf(z,Se.TEXTURE_MAX_ANISOTROPY_EXT,Math.min($.anisotropy,r.getMaxAnisotropy())),s.get($).__currentAnisotropy=$.anisotropy)}}function j(z,$){let ue=!1;z.__webglInit===void 0&&(z.__webglInit=!0,$.addEventListener("dispose",T));const Se=$.source;let ye=d.get(Se);ye===void 0&&(ye={},d.set(Se,ye));const Ce=P($);if(Ce!==z.__cacheKey){ye[Ce]===void 0&&(ye[Ce]={texture:n.createTexture(),usedTimes:0},o.memory.textures++,ue=!0),ye[Ce].usedTimes++;const Ze=ye[z.__cacheKey];Ze!==void 0&&(ye[z.__cacheKey].usedTimes--,Ze.usedTimes===0&&_($)),z.__cacheKey=Ce,z.__webglTexture=ye[Ce].texture}return ue}function ne(z,$,ue){let Se=n.TEXTURE_2D;($.isDataArrayTexture||$.isCompressedArrayTexture)&&(Se=n.TEXTURE_2D_ARRAY),$.isData3DTexture&&(Se=n.TEXTURE_3D);const ye=j(z,$),Ce=$.source;t.bindTexture(Se,z.__webglTexture,n.TEXTURE0+ue);const Ze=s.get(Ce);if(Ce.version!==Ze.__version||ye===!0){t.activeTexture(n.TEXTURE0+ue);const Fe=cn.getPrimaries(cn.workingColorSpace),je=$.colorSpace===qr?null:cn.getPrimaries($.colorSpace),ot=$.colorSpace===qr||Fe===je?n.NONE:n.BROWSER_DEFAULT_WEBGL;n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,$.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,$.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,$.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,ot);const xt=g($)&&m($.image)===!1;let Ie=x($.image,xt,!1,r.maxTextureSize);Ie=Je($,Ie);const Zt=m(Ie)||a,zt=i.convert($.format,$.colorSpace);let wt=i.convert($.type),ht=y($.internalFormat,zt,wt,$.colorSpace,$.isVideoTexture);he(Se,$,Zt);let rt;const Pt=$.mipmaps,rn=a&&$.isVideoTexture!==!0&&ht!==qk,_n=Ze.__version===void 0||ye===!0,Gt=Ce.dataReady,dn=w($,Ie,Zt);if($.isDepthTexture)ht=n.DEPTH_COMPONENT,a?$.type===yo?ht=n.DEPTH_COMPONENT32F:$.type===Zo?ht=n.DEPTH_COMPONENT24:$.type===cl?ht=n.DEPTH24_STENCIL8:ht=n.DEPTH_COMPONENT16:$.type===yo&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),$.format===ul&&ht===n.DEPTH_COMPONENT&&$.type!==lb&&$.type!==Zo&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),$.type=Zo,wt=i.convert($.type)),$.format===Wc&&ht===n.DEPTH_COMPONENT&&(ht=n.DEPTH_STENCIL,$.type!==cl&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),$.type=cl,wt=i.convert($.type))),_n&&(rn?t.texStorage2D(n.TEXTURE_2D,1,ht,Ie.width,Ie.height):t.texImage2D(n.TEXTURE_2D,0,ht,Ie.width,Ie.height,0,zt,wt,null));else if($.isDataTexture)if(Pt.length>0&&Zt){rn&&_n&&t.texStorage2D(n.TEXTURE_2D,dn,ht,Pt[0].width,Pt[0].height);for(let W=0,Oe=Pt.length;W>=1,Oe>>=1}}else if(Pt.length>0&&Zt){rn&&_n&&t.texStorage2D(n.TEXTURE_2D,dn,ht,Pt[0].width,Pt[0].height);for(let W=0,Oe=Pt.length;W0&&Gt++,t.texStorage2D(n.TEXTURE_CUBE_MAP,Gt,rt,Ie[0].width,Ie[0].height));for(let W=0;W<6;W++)if(xt){Pt?_n&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+W,0,0,0,Ie[W].width,Ie[W].height,wt,ht,Ie[W].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+W,0,rt,Ie[W].width,Ie[W].height,0,wt,ht,Ie[W].data);for(let Oe=0;Oe>Ce),Ie=Math.max(1,$.height>>Ce);ye===n.TEXTURE_3D||ye===n.TEXTURE_2D_ARRAY?t.texImage3D(ye,Ce,je,xt,Ie,$.depth,0,Ze,Fe,null):t.texImage2D(ye,Ce,je,xt,Ie,0,Ze,Fe,null)}t.bindFramebuffer(n.FRAMEBUFFER,z),Pe($)?l.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,Se,ye,s.get(ue).__webglTexture,0,Ke($)):(ye===n.TEXTURE_2D||ye>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&ye<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,Se,ye,s.get(ue).__webglTexture,Ce),t.bindFramebuffer(n.FRAMEBUFFER,null)}function Te(z,$,ue){if(n.bindRenderbuffer(n.RENDERBUFFER,z),$.depthBuffer&&!$.stencilBuffer){let Se=a===!0?n.DEPTH_COMPONENT24:n.DEPTH_COMPONENT16;if(ue||Pe($)){const ye=$.depthTexture;ye&&ye.isDepthTexture&&(ye.type===yo?Se=n.DEPTH_COMPONENT32F:ye.type===Zo&&(Se=n.DEPTH_COMPONENT24));const Ce=Ke($);Pe($)?l.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,Ce,Se,$.width,$.height):n.renderbufferStorageMultisample(n.RENDERBUFFER,Ce,Se,$.width,$.height)}else n.renderbufferStorage(n.RENDERBUFFER,Se,$.width,$.height);n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,z)}else if($.depthBuffer&&$.stencilBuffer){const Se=Ke($);ue&&Pe($)===!1?n.renderbufferStorageMultisample(n.RENDERBUFFER,Se,n.DEPTH24_STENCIL8,$.width,$.height):Pe($)?l.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,Se,n.DEPTH24_STENCIL8,$.width,$.height):n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH_STENCIL,$.width,$.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,z)}else{const Se=$.isWebGLMultipleRenderTargets===!0?$.texture:[$.texture];for(let ye=0;ye0){ue.__webglFramebuffer[Fe]=[];for(let je=0;je<$.mipmaps.length;je++)ue.__webglFramebuffer[Fe][je]=n.createFramebuffer()}else ue.__webglFramebuffer[Fe]=n.createFramebuffer()}else{if(a&&$.mipmaps&&$.mipmaps.length>0){ue.__webglFramebuffer=[];for(let Fe=0;Fe<$.mipmaps.length;Fe++)ue.__webglFramebuffer[Fe]=n.createFramebuffer()}else ue.__webglFramebuffer=n.createFramebuffer();if(Ce)if(r.drawBuffers){const Fe=z.texture;for(let je=0,ot=Fe.length;je0&&Pe(z)===!1){const Fe=Ce?$:[$];ue.__webglMultisampledFramebuffer=n.createFramebuffer(),ue.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,ue.__webglMultisampledFramebuffer);for(let je=0;je0)for(let je=0;je<$.mipmaps.length;je++)be(ue.__webglFramebuffer[Fe][je],z,$,n.COLOR_ATTACHMENT0,n.TEXTURE_CUBE_MAP_POSITIVE_X+Fe,je);else be(ue.__webglFramebuffer[Fe],z,$,n.COLOR_ATTACHMENT0,n.TEXTURE_CUBE_MAP_POSITIVE_X+Fe,0);v($,Ze)&&b(n.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(Ce){const Fe=z.texture;for(let je=0,ot=Fe.length;je0)for(let je=0;je<$.mipmaps.length;je++)be(ue.__webglFramebuffer[je],z,$,n.COLOR_ATTACHMENT0,Fe,je);else be(ue.__webglFramebuffer,z,$,n.COLOR_ATTACHMENT0,Fe,0);v($,Ze)&&b(Fe),t.unbindTexture()}z.depthBuffer&&Ge(z)}function mt(z){const $=m(z)||a,ue=z.isWebGLMultipleRenderTargets===!0?z.texture:[z.texture];for(let Se=0,ye=ue.length;Se0&&Pe(z)===!1){const $=z.isWebGLMultipleRenderTargets?z.texture:[z.texture],ue=z.width,Se=z.height;let ye=n.COLOR_BUFFER_BIT;const Ce=[],Ze=z.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,Fe=s.get(z),je=z.isWebGLMultipleRenderTargets===!0;if(je)for(let ot=0;ot<$.length;ot++)t.bindFramebuffer(n.FRAMEBUFFER,Fe.__webglMultisampledFramebuffer),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+ot,n.RENDERBUFFER,null),t.bindFramebuffer(n.FRAMEBUFFER,Fe.__webglFramebuffer),n.framebufferTexture2D(n.DRAW_FRAMEBUFFER,n.COLOR_ATTACHMENT0+ot,n.TEXTURE_2D,null,0);t.bindFramebuffer(n.READ_FRAMEBUFFER,Fe.__webglMultisampledFramebuffer),t.bindFramebuffer(n.DRAW_FRAMEBUFFER,Fe.__webglFramebuffer);for(let ot=0;ot<$.length;ot++){Ce.push(n.COLOR_ATTACHMENT0+ot),z.depthBuffer&&Ce.push(Ze);const xt=Fe.__ignoreDepthValues!==void 0?Fe.__ignoreDepthValues:!1;if(xt===!1&&(z.depthBuffer&&(ye|=n.DEPTH_BUFFER_BIT),z.stencilBuffer&&(ye|=n.STENCIL_BUFFER_BIT)),je&&n.framebufferRenderbuffer(n.READ_FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.RENDERBUFFER,Fe.__webglColorRenderbuffer[ot]),xt===!0&&(n.invalidateFramebuffer(n.READ_FRAMEBUFFER,[Ze]),n.invalidateFramebuffer(n.DRAW_FRAMEBUFFER,[Ze])),je){const Ie=s.get($[ot]).__webglTexture;n.framebufferTexture2D(n.DRAW_FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,Ie,0)}n.blitFramebuffer(0,0,ue,Se,0,0,ue,Se,ye,n.NEAREST),c&&n.invalidateFramebuffer(n.READ_FRAMEBUFFER,Ce)}if(t.bindFramebuffer(n.READ_FRAMEBUFFER,null),t.bindFramebuffer(n.DRAW_FRAMEBUFFER,null),je)for(let ot=0;ot<$.length;ot++){t.bindFramebuffer(n.FRAMEBUFFER,Fe.__webglMultisampledFramebuffer),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+ot,n.RENDERBUFFER,Fe.__webglColorRenderbuffer[ot]);const xt=s.get($[ot]).__webglTexture;t.bindFramebuffer(n.FRAMEBUFFER,Fe.__webglFramebuffer),n.framebufferTexture2D(n.DRAW_FRAMEBUFFER,n.COLOR_ATTACHMENT0+ot,n.TEXTURE_2D,xt,0)}t.bindFramebuffer(n.DRAW_FRAMEBUFFER,Fe.__webglMultisampledFramebuffer)}}function Ke(z){return Math.min(r.maxSamples,z.samples)}function Pe(z){const $=s.get(z);return a&&z.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&$.__useRenderToTexture!==!1}function gt(z){const $=o.render.frame;u.get(z)!==$&&(u.set(z,$),z.update())}function Je(z,$){const ue=z.colorSpace,Se=z.format,ye=z.type;return z.isCompressedTexture===!0||z.isVideoTexture===!0||z.format===Fx||ue!==Ro&&ue!==qr&&(cn.getTransfer(ue)===Tn?a===!1?e.has("EXT_sRGB")===!0&&Se===mi?(z.format=Fx,z.minFilter=ur,z.generateMipmaps=!1):$=Yk.sRGBToLinear($):(Se!==mi||ye!==ia)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",ue)),$}this.allocateTextureUnit=M,this.resetTextureUnits=B,this.setTexture2D=L,this.setTexture2DArray=q,this.setTexture3D=U,this.setTextureCube=X,this.rebindTextures=$e,this.setupRenderTarget=te,this.updateRenderTargetMipmap=mt,this.updateMultisampleRenderTarget=Ve,this.setupDepthRenderbuffer=Ge,this.setupFrameBufferTexture=be,this.useMultisampledRTT=Pe}function ame(n,e,t){const s=t.isWebGL2;function r(i,o=qr){let a;const l=cn.getTransfer(o);if(i===ia)return n.UNSIGNED_BYTE;if(i===Uk)return n.UNSIGNED_SHORT_4_4_4_4;if(i===Vk)return n.UNSIGNED_SHORT_5_5_5_1;if(i===Uue)return n.BYTE;if(i===Vue)return n.SHORT;if(i===lb)return n.UNSIGNED_SHORT;if(i===Bk)return n.INT;if(i===Zo)return n.UNSIGNED_INT;if(i===yo)return n.FLOAT;if(i===Jh)return s?n.HALF_FLOAT:(a=e.get("OES_texture_half_float"),a!==null?a.HALF_FLOAT_OES:null);if(i===Wue)return n.ALPHA;if(i===mi)return n.RGBA;if(i===Gue)return n.LUMINANCE;if(i===Hue)return n.LUMINANCE_ALPHA;if(i===ul)return n.DEPTH_COMPONENT;if(i===Wc)return n.DEPTH_STENCIL;if(i===Fx)return a=e.get("EXT_sRGB"),a!==null?a.SRGB_ALPHA_EXT:null;if(i===que)return n.RED;if(i===Wk)return n.RED_INTEGER;if(i===Xue)return n.RG;if(i===Gk)return n.RG_INTEGER;if(i===Hk)return n.RGBA_INTEGER;if(i===Xg||i===Kg||i===jg||i===Yg)if(l===Tn)if(a=e.get("WEBGL_compressed_texture_s3tc_srgb"),a!==null){if(i===Xg)return a.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===Kg)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===jg)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Yg)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(a=e.get("WEBGL_compressed_texture_s3tc"),a!==null){if(i===Xg)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===Kg)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===jg)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Yg)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===Kw||i===jw||i===Yw||i===Zw)if(a=e.get("WEBGL_compressed_texture_pvrtc"),a!==null){if(i===Kw)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===jw)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Yw)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Zw)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===qk)return a=e.get("WEBGL_compressed_texture_etc1"),a!==null?a.COMPRESSED_RGB_ETC1_WEBGL:null;if(i===Jw||i===Qw)if(a=e.get("WEBGL_compressed_texture_etc"),a!==null){if(i===Jw)return l===Tn?a.COMPRESSED_SRGB8_ETC2:a.COMPRESSED_RGB8_ETC2;if(i===Qw)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:a.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===e3||i===t3||i===n3||i===s3||i===r3||i===i3||i===o3||i===a3||i===l3||i===c3||i===u3||i===h3||i===d3||i===p3)if(a=e.get("WEBGL_compressed_texture_astc"),a!==null){if(i===e3)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:a.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===t3)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:a.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===n3)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:a.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===s3)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:a.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===r3)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:a.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===i3)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:a.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===o3)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:a.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===a3)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:a.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===l3)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:a.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===c3)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:a.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===u3)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:a.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===h3)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:a.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===d3)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:a.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===p3)return l===Tn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:a.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===Zg||i===f3||i===m3)if(a=e.get("EXT_texture_compression_bptc"),a!==null){if(i===Zg)return l===Tn?a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:a.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===f3)return a.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===m3)return a.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===Kue||i===g3||i===x3||i===v3)if(a=e.get("EXT_texture_compression_rgtc"),a!==null){if(i===Zg)return a.COMPRESSED_RED_RGTC1_EXT;if(i===g3)return a.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===x3)return a.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===v3)return a.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===cl?s?n.UNSIGNED_INT_24_8:(a=e.get("WEBGL_depth_texture"),a!==null?a.UNSIGNED_INT_24_8_WEBGL:null):n[i]!==void 0?n[i]:null}return{convert:r}}class lme extends pi{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class xi extends Ar{constructor(){super(),this.isGroup=!0,this.type="Group"}}const cme={type:"move"};class S1{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new xi,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new xi,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new fe,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new fe),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new xi,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new fe,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new fe),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const s of e.hand.values())this._getHandJoint(t,s)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,s){let r=null,i=null,o=null;const a=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){o=!0;for(const x of e.hand.values()){const m=t.getJointPose(x,s),g=this._getHandJoint(c,x);m!==null&&(g.matrix.fromArray(m.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=m.radius),g.visible=m!==null}const u=c.joints["index-finger-tip"],h=c.joints["thumb-tip"],d=u.position.distanceTo(h.position),p=.02,f=.005;c.inputState.pinching&&d>p+f?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&d<=p-f&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,s),i!==null&&(l.matrix.fromArray(i.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,i.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(i.linearVelocity)):l.hasLinearVelocity=!1,i.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(i.angularVelocity)):l.hasAngularVelocity=!1));a!==null&&(r=t.getPose(e.targetRaySpace,s),r===null&&i!==null&&(r=i),r!==null&&(a.matrix.fromArray(r.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,r.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(r.linearVelocity)):a.hasLinearVelocity=!1,r.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(r.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(cme)))}return a!==null&&(a.visible=r!==null),l!==null&&(l.visible=i!==null),c!==null&&(c.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const s=new xi;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}const ume=` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`,hme=` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepthEXT = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepthEXT = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`;class dme{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,s){if(this.texture===null){const r=new gr,i=e.properties.get(r);i.__webglTexture=t.texture,(t.depthNear!=s.depthNear||t.depthFar!=s.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=r}}render(e,t){if(this.texture!==null){if(this.mesh===null){const s=t.cameras[0].viewport,r=new fa({extensions:{fragDepth:!0},vertexShader:ume,fragmentShader:hme,uniforms:{depthColor:{value:this.texture},depthWidth:{value:s.z},depthHeight:{value:s.w}}});this.mesh=new Qn(new Jr(20,20),r)}e.render(this.mesh,t)}}reset(){this.texture=null,this.mesh=null}}class pme extends oh{constructor(e,t){super();const s=this;let r=null,i=1,o=null,a="local-floor",l=1,c=null,u=null,h=null,d=null,p=null,f=null;const x=new dme,m=t.getContextAttributes();let g=null,v=null;const b=[],y=[],w=new en;let C=null;const T=new pi;T.layers.enable(1),T.viewport=new Es;const E=new pi;E.layers.enable(2),E.viewport=new Es;const R=[T,E],_=new lme;_.layers.enable(1),_.layers.enable(2);let k=null,F=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(j){let ne=b[j];return ne===void 0&&(ne=new S1,b[j]=ne),ne.getTargetRaySpace()},this.getControllerGrip=function(j){let ne=b[j];return ne===void 0&&(ne=new S1,b[j]=ne),ne.getGripSpace()},this.getHand=function(j){let ne=b[j];return ne===void 0&&(ne=new S1,b[j]=ne),ne.getHandSpace()};function B(j){const ne=y.indexOf(j.inputSource);if(ne===-1)return;const ge=b[ne];ge!==void 0&&(ge.update(j.inputSource,j.frame,c||o),ge.dispatchEvent({type:j.type,data:j.inputSource}))}function M(){r.removeEventListener("select",B),r.removeEventListener("selectstart",B),r.removeEventListener("selectend",B),r.removeEventListener("squeeze",B),r.removeEventListener("squeezestart",B),r.removeEventListener("squeezeend",B),r.removeEventListener("end",M),r.removeEventListener("inputsourceschange",P);for(let j=0;j=0&&(y[be]=null,b[be].disconnect(ge))}for(let ne=0;ne=y.length){y.push(ge),be=ve;break}else if(y[ve]===null){y[ve]=ge,be=ve;break}if(be===-1)break}const Te=b[be];Te&&Te.connect(ge)}}const L=new fe,q=new fe;function U(j,ne,ge){L.setFromMatrixPosition(ne.matrixWorld),q.setFromMatrixPosition(ge.matrixWorld);const be=L.distanceTo(q),Te=ne.projectionMatrix.elements,ve=ge.projectionMatrix.elements,Ge=Te[14]/(Te[10]-1),$e=Te[14]/(Te[10]+1),te=(Te[9]+1)/Te[5],mt=(Te[9]-1)/Te[5],Ve=(Te[8]-1)/Te[0],Ke=(ve[8]+1)/ve[0],Pe=Ge*Ve,gt=Ge*Ke,Je=be/(-Ve+Ke),z=Je*-Ve;ne.matrixWorld.decompose(j.position,j.quaternion,j.scale),j.translateX(z),j.translateZ(Je),j.matrixWorld.compose(j.position,j.quaternion,j.scale),j.matrixWorldInverse.copy(j.matrixWorld).invert();const $=Ge+Je,ue=$e+Je,Se=Pe-z,ye=gt+(be-z),Ce=te*$e/ue*$,Ze=mt*$e/ue*$;j.projectionMatrix.makePerspective(Se,ye,Ce,Ze,$,ue),j.projectionMatrixInverse.copy(j.projectionMatrix).invert()}function X(j,ne){ne===null?j.matrixWorld.copy(j.matrix):j.matrixWorld.multiplyMatrices(ne.matrixWorld,j.matrix),j.matrixWorldInverse.copy(j.matrixWorld).invert()}this.updateCamera=function(j){if(r===null)return;x.texture!==null&&(j.near=x.depthNear,j.far=x.depthFar),_.near=E.near=T.near=j.near,_.far=E.far=T.far=j.far,(k!==_.near||F!==_.far)&&(r.updateRenderState({depthNear:_.near,depthFar:_.far}),k=_.near,F=_.far,T.near=k,T.far=F,E.near=k,E.far=F,T.updateProjectionMatrix(),E.updateProjectionMatrix(),j.updateProjectionMatrix());const ne=j.parent,ge=_.cameras;X(_,ne);for(let be=0;be0&&(m.alphaTest.value=g.alphaTest);const v=e.get(g).envMap;if(v&&(m.envMap.value=v,m.flipEnvMap.value=v.isCubeTexture&&v.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=g.reflectivity,m.ior.value=g.ior,m.refractionRatio.value=g.refractionRatio),g.lightMap){m.lightMap.value=g.lightMap;const b=n._useLegacyLights===!0?Math.PI:1;m.lightMapIntensity.value=g.lightMapIntensity*b,t(g.lightMap,m.lightMapTransform)}g.aoMap&&(m.aoMap.value=g.aoMap,m.aoMapIntensity.value=g.aoMapIntensity,t(g.aoMap,m.aoMapTransform))}function o(m,g){m.diffuse.value.copy(g.color),m.opacity.value=g.opacity,g.map&&(m.map.value=g.map,t(g.map,m.mapTransform))}function a(m,g){m.dashSize.value=g.dashSize,m.totalSize.value=g.dashSize+g.gapSize,m.scale.value=g.scale}function l(m,g,v,b){m.diffuse.value.copy(g.color),m.opacity.value=g.opacity,m.size.value=g.size*v,m.scale.value=b*.5,g.map&&(m.map.value=g.map,t(g.map,m.uvTransform)),g.alphaMap&&(m.alphaMap.value=g.alphaMap,t(g.alphaMap,m.alphaMapTransform)),g.alphaTest>0&&(m.alphaTest.value=g.alphaTest)}function c(m,g){m.diffuse.value.copy(g.color),m.opacity.value=g.opacity,m.rotation.value=g.rotation,g.map&&(m.map.value=g.map,t(g.map,m.mapTransform)),g.alphaMap&&(m.alphaMap.value=g.alphaMap,t(g.alphaMap,m.alphaMapTransform)),g.alphaTest>0&&(m.alphaTest.value=g.alphaTest)}function u(m,g){m.specular.value.copy(g.specular),m.shininess.value=Math.max(g.shininess,1e-4)}function h(m,g){g.gradientMap&&(m.gradientMap.value=g.gradientMap)}function d(m,g){m.metalness.value=g.metalness,g.metalnessMap&&(m.metalnessMap.value=g.metalnessMap,t(g.metalnessMap,m.metalnessMapTransform)),m.roughness.value=g.roughness,g.roughnessMap&&(m.roughnessMap.value=g.roughnessMap,t(g.roughnessMap,m.roughnessMapTransform)),e.get(g).envMap&&(m.envMapIntensity.value=g.envMapIntensity)}function p(m,g,v){m.ior.value=g.ior,g.sheen>0&&(m.sheenColor.value.copy(g.sheenColor).multiplyScalar(g.sheen),m.sheenRoughness.value=g.sheenRoughness,g.sheenColorMap&&(m.sheenColorMap.value=g.sheenColorMap,t(g.sheenColorMap,m.sheenColorMapTransform)),g.sheenRoughnessMap&&(m.sheenRoughnessMap.value=g.sheenRoughnessMap,t(g.sheenRoughnessMap,m.sheenRoughnessMapTransform))),g.clearcoat>0&&(m.clearcoat.value=g.clearcoat,m.clearcoatRoughness.value=g.clearcoatRoughness,g.clearcoatMap&&(m.clearcoatMap.value=g.clearcoatMap,t(g.clearcoatMap,m.clearcoatMapTransform)),g.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=g.clearcoatRoughnessMap,t(g.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),g.clearcoatNormalMap&&(m.clearcoatNormalMap.value=g.clearcoatNormalMap,t(g.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(g.clearcoatNormalScale),g.side===mr&&m.clearcoatNormalScale.value.negate())),g.iridescence>0&&(m.iridescence.value=g.iridescence,m.iridescenceIOR.value=g.iridescenceIOR,m.iridescenceThicknessMinimum.value=g.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=g.iridescenceThicknessRange[1],g.iridescenceMap&&(m.iridescenceMap.value=g.iridescenceMap,t(g.iridescenceMap,m.iridescenceMapTransform)),g.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=g.iridescenceThicknessMap,t(g.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),g.transmission>0&&(m.transmission.value=g.transmission,m.transmissionSamplerMap.value=v.texture,m.transmissionSamplerSize.value.set(v.width,v.height),g.transmissionMap&&(m.transmissionMap.value=g.transmissionMap,t(g.transmissionMap,m.transmissionMapTransform)),m.thickness.value=g.thickness,g.thicknessMap&&(m.thicknessMap.value=g.thicknessMap,t(g.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=g.attenuationDistance,m.attenuationColor.value.copy(g.attenuationColor)),g.anisotropy>0&&(m.anisotropyVector.value.set(g.anisotropy*Math.cos(g.anisotropyRotation),g.anisotropy*Math.sin(g.anisotropyRotation)),g.anisotropyMap&&(m.anisotropyMap.value=g.anisotropyMap,t(g.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=g.specularIntensity,m.specularColor.value.copy(g.specularColor),g.specularColorMap&&(m.specularColorMap.value=g.specularColorMap,t(g.specularColorMap,m.specularColorMapTransform)),g.specularIntensityMap&&(m.specularIntensityMap.value=g.specularIntensityMap,t(g.specularIntensityMap,m.specularIntensityMapTransform))}function f(m,g){g.matcap&&(m.matcap.value=g.matcap)}function x(m,g){const v=e.get(g).light;m.referencePosition.value.setFromMatrixPosition(v.matrixWorld),m.nearDistance.value=v.shadow.camera.near,m.farDistance.value=v.shadow.camera.far}return{refreshFogUniforms:s,refreshMaterialUniforms:r}}function mme(n,e,t,s){let r={},i={},o=[];const a=t.isWebGL2?n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS):0;function l(v,b){const y=b.program;s.uniformBlockBinding(v,y)}function c(v,b){let y=r[v.id];y===void 0&&(f(v),y=u(v),r[v.id]=y,v.addEventListener("dispose",m));const w=b.program;s.updateUBOMapping(v,w);const C=e.render.frame;i[v.id]!==C&&(d(v),i[v.id]=C)}function u(v){const b=h();v.__bindingPointIndex=b;const y=n.createBuffer(),w=v.__size,C=v.usage;return n.bindBuffer(n.UNIFORM_BUFFER,y),n.bufferData(n.UNIFORM_BUFFER,w,C),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,b,y),y}function h(){for(let v=0;v0&&(y+=w-C),v.__size=y,v.__cache={},this}function x(v){const b={boundary:0,storage:0};return typeof v=="number"||typeof v=="boolean"?(b.boundary=4,b.storage=4):v.isVector2?(b.boundary=8,b.storage=8):v.isVector3||v.isColor?(b.boundary=16,b.storage=12):v.isVector4?(b.boundary=16,b.storage=16):v.isMatrix3?(b.boundary=48,b.storage=48):v.isMatrix4?(b.boundary=64,b.storage=64):v.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",v),b}function m(v){const b=v.target;b.removeEventListener("dispose",m);const y=o.indexOf(b.__bindingPointIndex);o.splice(y,1),n.deleteBuffer(r[b.id]),delete r[b.id],delete i[b.id]}function g(){for(const v in r)n.deleteBuffer(r[v]);o=[],r={},i={}}return{bind:l,update:c,dispose:g}}class mA{constructor(e={}){const{canvas:t=ahe(),context:s=null,depth:r=!0,stencil:i=!0,alpha:o=!1,antialias:a=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:h=!1}=e;this.isWebGLRenderer=!0;let d;s!==null?d=s.getContextAttributes().alpha:d=o;const p=new Uint32Array(4),f=new Int32Array(4);let x=null,m=null;const g=[],v=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=Is,this._useLegacyLights=!1,this.toneMapping=ra,this.toneMappingExposure=1;const b=this;let y=!1,w=0,C=0,T=null,E=-1,R=null;const _=new Es,k=new Es;let F=null;const B=new un(0);let M=0,P=t.width,L=t.height,q=1,U=null,X=null;const K=new Es(0,0,P,L),J=new Es(0,0,P,L);let ae=!1;const he=new oA;let j=!1,ne=!1,ge=null;const be=new ks,Te=new en,ve=new fe,Ge={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function $e(){return T===null?q:1}let te=s;function mt(O,ce){for(let pe=0;pe{function et(){if(xe.forEach(function(ct){Je.get(ct).currentProgram.isReady()&&xe.delete(ct)}),xe.size===0){de(O);return}setTimeout(et,10)}Ve.get("KHR_parallel_shader_compile")!==null?et():setTimeout(et,10)})};let vn=null;function Ts(O){vn&&vn(O)}function zr(){Ws.stop()}function bn(){Ws.start()}const Ws=new aA;Ws.setAnimationLoop(Ts),typeof self<"u"&&Ws.setContext(self),this.setAnimationLoop=function(O){vn=O,Gt.setAnimationLoop(O),O===null?Ws.stop():Ws.start()},Gt.addEventListener("sessionstart",zr),Gt.addEventListener("sessionend",bn),this.render=function(O,ce){if(ce!==void 0&&ce.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(y===!0)return;O.matrixWorldAutoUpdate===!0&&O.updateMatrixWorld(),ce.parent===null&&ce.matrixWorldAutoUpdate===!0&&ce.updateMatrixWorld(),Gt.enabled===!0&&Gt.isPresenting===!0&&(Gt.cameraAutoUpdate===!0&&Gt.updateCamera(ce),ce=Gt.getCamera()),O.isScene===!0&&O.onBeforeRender(b,O,ce,T),m=ot.get(O,v.length),m.init(),v.push(m),be.multiplyMatrices(ce.projectionMatrix,ce.matrixWorldInverse),he.setFromProjectionMatrix(be),ne=this.localClippingEnabled,j=xt.init(this.clippingPlanes,ne),x=je.get(O,g.length),x.init(),g.push(x),Ni(O,ce,0,b.sortObjects),x.finish(),b.sortObjects===!0&&x.sort(U,X),this.info.render.frame++,j===!0&&xt.beginShadows();const pe=m.state.shadowsArray;if(Ie.render(pe,O,ce),j===!0&&xt.endShadows(),this.info.autoReset===!0&&this.info.reset(),(Gt.enabled===!1||Gt.isPresenting===!1||Gt.hasDepthSensing()===!1)&&Zt.render(x,O),m.setupLights(b._useLegacyLights),ce.isArrayCamera){const xe=ce.cameras;for(let de=0,et=xe.length;de0?m=v[v.length-1]:m=null,g.pop(),g.length>0?x=g[g.length-1]:x=null};function Ni(O,ce,pe,xe){if(O.visible===!1)return;if(O.layers.test(ce.layers)){if(O.isGroup)pe=O.renderOrder;else if(O.isLOD)O.autoUpdate===!0&&O.update(ce);else if(O.isLight)m.pushLight(O),O.castShadow&&m.pushShadow(O);else if(O.isSprite){if(!O.frustumCulled||he.intersectsSprite(O)){xe&&ve.setFromMatrixPosition(O.matrixWorld).applyMatrix4(be);const ct=Ce.update(O),St=O.material;St.visible&&x.push(O,ct,St,pe,ve.z,null)}}else if((O.isMesh||O.isLine||O.isPoints)&&(!O.frustumCulled||he.intersectsObject(O))){const ct=Ce.update(O),St=O.material;if(xe&&(O.boundingSphere!==void 0?(O.boundingSphere===null&&O.computeBoundingSphere(),ve.copy(O.boundingSphere.center)):(ct.boundingSphere===null&&ct.computeBoundingSphere(),ve.copy(ct.boundingSphere.center)),ve.applyMatrix4(O.matrixWorld).applyMatrix4(be)),Array.isArray(St)){const Et=ct.groups;for(let Bt=0,At=Et.length;Bt0&&pR(de,et,ce,pe),xe&&Pe.viewport(_.copy(xe)),de.length>0&&Ap(de,ce,pe),et.length>0&&Ap(et,ce,pe),ct.length>0&&Ap(ct,ce,pe),Pe.buffers.depth.setTest(!0),Pe.buffers.depth.setMask(!0),Pe.buffers.color.setMask(!0),Pe.setPolygonOffset(!1)}function pR(O,ce,pe,xe){if((pe.isScene===!0?pe.overrideMaterial:null)!==null)return;const et=Ke.isWebGL2;ge===null&&(ge=new Tl(1,1,{generateMipmaps:!0,type:Ve.has("EXT_color_buffer_half_float")?Jh:ia,minFilter:sl,samples:et?4:0})),b.getDrawingBufferSize(Te),et?ge.setSize(Te.x,Te.y):ge.setSize(zx(Te.x),zx(Te.y));const ct=b.getRenderTarget();b.setRenderTarget(ge),b.getClearColor(B),M=b.getClearAlpha(),M<1&&b.setClearColor(16777215,.5),b.clear();const St=b.toneMapping;b.toneMapping=ra,Ap(O,pe,xe),z.updateMultisampleRenderTarget(ge),z.updateRenderTargetMipmap(ge);let Et=!1;for(let Bt=0,At=ce.length;Bt0),$t=!!pe.morphAttributes.position,qn=!!pe.morphAttributes.normal,Sr=!!pe.morphAttributes.color;let vs=ra;xe.toneMapped&&(T===null||T.isXRRenderTarget===!0)&&(vs=b.toneMapping);const lo=pe.morphAttributes.position||pe.morphAttributes.normal||pe.morphAttributes.color,Nn=lo!==void 0?lo.length:0,Ut=Je.get(xe),Sg=m.state.lights;if(j===!0&&(ne===!0||O!==R)){const Br=O===R&&xe.id===E;xt.setState(xe,O,Br)}let Ln=!1;xe.version===Ut.__version?(Ut.needsLights&&Ut.lightsStateVersion!==Sg.state.version||Ut.outputColorSpace!==St||de.isBatchedMesh&&Ut.batching===!1||!de.isBatchedMesh&&Ut.batching===!0||de.isInstancedMesh&&Ut.instancing===!1||!de.isInstancedMesh&&Ut.instancing===!0||de.isSkinnedMesh&&Ut.skinning===!1||!de.isSkinnedMesh&&Ut.skinning===!0||de.isInstancedMesh&&Ut.instancingColor===!0&&de.instanceColor===null||de.isInstancedMesh&&Ut.instancingColor===!1&&de.instanceColor!==null||Ut.envMap!==Et||xe.fog===!0&&Ut.fog!==et||Ut.numClippingPlanes!==void 0&&(Ut.numClippingPlanes!==xt.numPlanes||Ut.numIntersection!==xt.numIntersection)||Ut.vertexAlphas!==Bt||Ut.vertexTangents!==At||Ut.morphTargets!==$t||Ut.morphNormals!==qn||Ut.morphColors!==Sr||Ut.toneMapping!==vs||Ke.isWebGL2===!0&&Ut.morphTargetsCount!==Nn)&&(Ln=!0):(Ln=!0,Ut.__version=xe.version);let Na=Ut.currentProgram;Ln===!0&&(Na=Rp(xe,ce,de));let $b=!1,dh=!1,Cg=!1;const $s=Na.getUniforms(),$a=Ut.uniforms;if(Pe.useProgram(Na.program)&&($b=!0,dh=!0,Cg=!0),xe.id!==E&&(E=xe.id,dh=!0),$b||R!==O){$s.setValue(te,"projectionMatrix",O.projectionMatrix),$s.setValue(te,"viewMatrix",O.matrixWorldInverse);const Br=$s.map.cameraPosition;Br!==void 0&&Br.setValue(te,ve.setFromMatrixPosition(O.matrixWorld)),Ke.logarithmicDepthBuffer&&$s.setValue(te,"logDepthBufFC",2/(Math.log(O.far+1)/Math.LN2)),(xe.isMeshPhongMaterial||xe.isMeshToonMaterial||xe.isMeshLambertMaterial||xe.isMeshBasicMaterial||xe.isMeshStandardMaterial||xe.isShaderMaterial)&&$s.setValue(te,"isOrthographic",O.isOrthographicCamera===!0),R!==O&&(R=O,dh=!0,Cg=!0)}if(de.isSkinnedMesh){$s.setOptional(te,de,"bindMatrix"),$s.setOptional(te,de,"bindMatrixInverse");const Br=de.skeleton;Br&&(Ke.floatVertexTextures?(Br.boneTexture===null&&Br.computeBoneTexture(),$s.setValue(te,"boneTexture",Br.boneTexture,z)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}de.isBatchedMesh&&($s.setOptional(te,de,"batchingTexture"),$s.setValue(te,"batchingTexture",de._matricesTexture,z));const _g=pe.morphAttributes;if((_g.position!==void 0||_g.normal!==void 0||_g.color!==void 0&&Ke.isWebGL2===!0)&&zt.update(de,pe,Na),(dh||Ut.receiveShadow!==de.receiveShadow)&&(Ut.receiveShadow=de.receiveShadow,$s.setValue(te,"receiveShadow",de.receiveShadow)),xe.isMeshGouraudMaterial&&xe.envMap!==null&&($a.envMap.value=Et,$a.flipEnvMap.value=Et.isCubeTexture&&Et.isRenderTargetTexture===!1?-1:1),dh&&($s.setValue(te,"toneMappingExposure",b.toneMappingExposure),Ut.needsLights&&mR($a,Cg),et&&xe.fog===!0&&Fe.refreshFogUniforms($a,et),Fe.refreshMaterialUniforms($a,xe,q,L,ge),If.upload(te,Mb(Ut),$a,z)),xe.isShaderMaterial&&xe.uniformsNeedUpdate===!0&&(If.upload(te,Mb(Ut),$a,z),xe.uniformsNeedUpdate=!1),xe.isSpriteMaterial&&$s.setValue(te,"center",de.center),$s.setValue(te,"modelViewMatrix",de.modelViewMatrix),$s.setValue(te,"normalMatrix",de.normalMatrix),$s.setValue(te,"modelMatrix",de.matrixWorld),xe.isShaderMaterial||xe.isRawShaderMaterial){const Br=xe.uniformsGroups;for(let Tg=0,xR=Br.length;Tg0&&z.useMultisampledRTT(O)===!1?de=Je.get(O).__webglMultisampledFramebuffer:Array.isArray(At)?de=At[pe]:de=At,_.copy(O.viewport),k.copy(O.scissor),F=O.scissorTest}else _.copy(K).multiplyScalar(q).floor(),k.copy(J).multiplyScalar(q).floor(),F=ae;if(Pe.bindFramebuffer(te.FRAMEBUFFER,de)&&Ke.drawBuffers&&xe&&Pe.drawBuffers(O,de),Pe.viewport(_),Pe.scissor(k),Pe.setScissorTest(F),et){const Et=Je.get(O.texture);te.framebufferTexture2D(te.FRAMEBUFFER,te.COLOR_ATTACHMENT0,te.TEXTURE_CUBE_MAP_POSITIVE_X+ce,Et.__webglTexture,pe)}else if(ct){const Et=Je.get(O.texture),Bt=ce||0;te.framebufferTextureLayer(te.FRAMEBUFFER,te.COLOR_ATTACHMENT0,Et.__webglTexture,pe||0,Bt)}E=-1},this.readRenderTargetPixels=function(O,ce,pe,xe,de,et,ct){if(!(O&&O.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let St=Je.get(O).__webglFramebuffer;if(O.isWebGLCubeRenderTarget&&ct!==void 0&&(St=St[ct]),St){Pe.bindFramebuffer(te.FRAMEBUFFER,St);try{const Et=O.texture,Bt=Et.format,At=Et.type;if(Bt!==mi&&rt.convert(Bt)!==te.getParameter(te.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}const $t=At===Jh&&(Ve.has("EXT_color_buffer_half_float")||Ke.isWebGL2&&Ve.has("EXT_color_buffer_float"));if(At!==ia&&rt.convert(At)!==te.getParameter(te.IMPLEMENTATION_COLOR_READ_TYPE)&&!(At===yo&&(Ke.isWebGL2||Ve.has("OES_texture_float")||Ve.has("WEBGL_color_buffer_float")))&&!$t){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}ce>=0&&ce<=O.width-xe&&pe>=0&&pe<=O.height-de&&te.readPixels(ce,pe,xe,de,rt.convert(Bt),rt.convert(At),et)}finally{const Et=T!==null?Je.get(T).__webglFramebuffer:null;Pe.bindFramebuffer(te.FRAMEBUFFER,Et)}}},this.copyFramebufferToTexture=function(O,ce,pe=0){const xe=Math.pow(2,-pe),de=Math.floor(ce.image.width*xe),et=Math.floor(ce.image.height*xe);z.setTexture2D(ce,0),te.copyTexSubImage2D(te.TEXTURE_2D,pe,0,0,O.x,O.y,de,et),Pe.unbindTexture()},this.copyTextureToTexture=function(O,ce,pe,xe=0){const de=ce.image.width,et=ce.image.height,ct=rt.convert(pe.format),St=rt.convert(pe.type);z.setTexture2D(pe,0),te.pixelStorei(te.UNPACK_FLIP_Y_WEBGL,pe.flipY),te.pixelStorei(te.UNPACK_PREMULTIPLY_ALPHA_WEBGL,pe.premultiplyAlpha),te.pixelStorei(te.UNPACK_ALIGNMENT,pe.unpackAlignment),ce.isDataTexture?te.texSubImage2D(te.TEXTURE_2D,xe,O.x,O.y,de,et,ct,St,ce.image.data):ce.isCompressedTexture?te.compressedTexSubImage2D(te.TEXTURE_2D,xe,O.x,O.y,ce.mipmaps[0].width,ce.mipmaps[0].height,ct,ce.mipmaps[0].data):te.texSubImage2D(te.TEXTURE_2D,xe,O.x,O.y,ct,St,ce.image),xe===0&&pe.generateMipmaps&&te.generateMipmap(te.TEXTURE_2D),Pe.unbindTexture()},this.copyTextureToTexture3D=function(O,ce,pe,xe,de=0){if(b.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}const et=O.max.x-O.min.x+1,ct=O.max.y-O.min.y+1,St=O.max.z-O.min.z+1,Et=rt.convert(xe.format),Bt=rt.convert(xe.type);let At;if(xe.isData3DTexture)z.setTexture3D(xe,0),At=te.TEXTURE_3D;else if(xe.isDataArrayTexture||xe.isCompressedArrayTexture)z.setTexture2DArray(xe,0),At=te.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}te.pixelStorei(te.UNPACK_FLIP_Y_WEBGL,xe.flipY),te.pixelStorei(te.UNPACK_PREMULTIPLY_ALPHA_WEBGL,xe.premultiplyAlpha),te.pixelStorei(te.UNPACK_ALIGNMENT,xe.unpackAlignment);const $t=te.getParameter(te.UNPACK_ROW_LENGTH),qn=te.getParameter(te.UNPACK_IMAGE_HEIGHT),Sr=te.getParameter(te.UNPACK_SKIP_PIXELS),vs=te.getParameter(te.UNPACK_SKIP_ROWS),lo=te.getParameter(te.UNPACK_SKIP_IMAGES),Nn=pe.isCompressedTexture?pe.mipmaps[de]:pe.image;te.pixelStorei(te.UNPACK_ROW_LENGTH,Nn.width),te.pixelStorei(te.UNPACK_IMAGE_HEIGHT,Nn.height),te.pixelStorei(te.UNPACK_SKIP_PIXELS,O.min.x),te.pixelStorei(te.UNPACK_SKIP_ROWS,O.min.y),te.pixelStorei(te.UNPACK_SKIP_IMAGES,O.min.z),pe.isDataTexture||pe.isData3DTexture?te.texSubImage3D(At,de,ce.x,ce.y,ce.z,et,ct,St,Et,Bt,Nn.data):pe.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),te.compressedTexSubImage3D(At,de,ce.x,ce.y,ce.z,et,ct,St,Et,Nn.data)):te.texSubImage3D(At,de,ce.x,ce.y,ce.z,et,ct,St,Et,Bt,Nn),te.pixelStorei(te.UNPACK_ROW_LENGTH,$t),te.pixelStorei(te.UNPACK_IMAGE_HEIGHT,qn),te.pixelStorei(te.UNPACK_SKIP_PIXELS,Sr),te.pixelStorei(te.UNPACK_SKIP_ROWS,vs),te.pixelStorei(te.UNPACK_SKIP_IMAGES,lo),de===0&&xe.generateMipmaps&&te.generateMipmap(At),Pe.unbindTexture()},this.initTexture=function(O){O.isCubeTexture?z.setTextureCube(O,0):O.isData3DTexture?z.setTexture3D(O,0):O.isDataArrayTexture||O.isCompressedArrayTexture?z.setTexture2DArray(O,0):z.setTexture2D(O,0),Pe.unbindTexture()},this.resetState=function(){w=0,C=0,T=null,Pe.reset(),Pt.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Co}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=e===cb?"display-p3":"srgb",t.unpackColorSpace=cn.workingColorSpace===ig?"display-p3":"srgb"}get outputEncoding(){return console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace===Is?hl:Xk}set outputEncoding(e){console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace=e===hl?Is:Ro}get useLegacyLights(){return console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights}set useLegacyLights(e){console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights=e}}class gme extends mA{}gme.prototype.isWebGL1Renderer=!0;class xme extends Ar{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t}}class Ip extends Ra{constructor(e=1,t=32,s=0,r=Math.PI*2){super(),this.type="CircleGeometry",this.parameters={radius:e,segments:t,thetaStart:s,thetaLength:r},t=Math.max(3,t);const i=[],o=[],a=[],l=[],c=new fe,u=new en;o.push(0,0,0),a.push(0,0,1),l.push(.5,.5);for(let h=0,d=3;h<=t;h++,d+=3){const p=s+h/t*r;c.x=e*Math.cos(p),c.y=e*Math.sin(p),o.push(c.x,c.y,c.z),a.push(0,0,1),u.x=(o[d]/e+1)/2,u.y=(o[d+1]/e+1)/2,l.push(u.x,u.y)}for(let h=1;h<=t;h++)i.push(h,h+1,0);this.setIndex(i),this.setAttribute("position",new Ki(o,3)),this.setAttribute("normal",new Ki(a,3)),this.setAttribute("uv",new Ki(l,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ip(e.radius,e.segments,e.thetaStart,e.thetaLength)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:ab}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=ab);const Js={sky:6067452,ground:10508842,groundDk:5909008,grass:2793546,bush:1997370,cloud:16777215,capRed:14694943,skin:16763036,overalls:2775760,boot:4861456,pole:13619412,flag:16729156};function vi(n){return new hb({color:n,side:Bi})}function vme(){const n=new xi,e=(t,s,r,i)=>{const o=new Qn(new Jr(t,s),vi(r));o.position.set(0,i,0),n.add(o)};return e(14,5,Js.capRed,-7.5),e(12,4,Js.skin,-3),e(14,9,Js.overalls,3.5),e(14,2,Js.boot,9),n}function cS(n,e,t=1){const s=new xi,r=[{x:-14,y:0,r:10},{x:0,y:-4,r:12},{x:14,y:0,r:10},{x:6,y:4,r:9},{x:-8,y:4,r:9}];for(const i of r){const o=new Qn(new Ip(i.r*t,20),vi(Js.cloud));o.position.set(i.x*t,i.y*t,0),s.add(o)}return s.position.set(n,e,0),s}function bme(n,e){const t=new xi,s=[{x:-16,y:0,r:12},{x:0,y:-4,r:14},{x:16,y:0,r:12}];for(const r of s){const i=new Qn(new Ip(r.r,16),vi(Js.bush));i.position.set(r.x,r.y,0),t.add(i)}return t.position.set(n,e,0),t}function yme(n,e){const t=new xi,s=80,r=new Qn(new Jr(3,s),vi(Js.pole));r.position.set(0,-s/2,0),t.add(r);const i=new Qn(new Jr(16,10),vi(Js.flag));i.position.set(10,-s+10,0),t.add(i);const o=new Qn(new Ip(3,12),vi(Js.pole));return o.position.set(0,-s,0),t.add(o),t.position.set(n,e,1),t}function wme(n){const e=new xi,t=new Qn(new Jr(n.width+2,22),vi(Js.groundDk));t.position.set(0,10,-.1),e.add(t);const s=new Qn(new Jr(n.width,20),vi(Js.ground));s.position.set(0,10,0),e.add(s);const r=new Qn(new Jr(n.width,3),vi(Js.grass));r.position.set(0,-1.5,.1),e.add(r);const o=Math.max(2,Math.round(n.width/26));for(let a=1;a{const o=e.clientWidth,a=e.clientHeight;this.renderer.setSize(o,a,!1)};r(),window.addEventListener("resize",r),e.appendChild(this.renderer.domElement);const i=new Qn(new Jr(t,s),vi(Js.sky));i.position.set(t/2,s/2,-8),this.scene.add(i),this.decor.position.z=-5,this.scene.add(this.decor),this.scene.add(this.platformGroup),this.agent=vme(),this.agent.position.z=2,this.scene.add(this.agent)}rebuildLevel(e){this.platformGroup.clear();for(const t of e.level.platforms)this.platformGroup.add(wme(t));this.goal&&this.scene.remove(this.goal),this.goal=yme(e.level.goalX,kn.floorY+10),this.scene.add(this.goal),this.decor.clear(),this.decor.add(cS(kn.width*.22,kn.height*.2,1)),this.decor.add(cS(kn.width*.7,kn.height*.3,.85)),this.decor.add(bme(kn.width*.5,kn.floorY-6))}draw(e){const t=e.level.platforms.map(s=>`${s.x}:${s.y}:${s.width}`).join("|");t!==this.lastLevelSignature&&(this.rebuildLevel(e),this.lastLevelSignature=t),this.agent.position.set(e.x+8,e.y+10,2),this.renderer.render(this.scene,this.camera)}}const bi=24,wo=64,Jo=4;class Cme{w1;b1;w2;b2;constructor(){const e=Math.sqrt(1/bi),t=Math.sqrt(1/wo);this.w1=tl(aa([bi,wo],-e,e)),this.b1=tl(On([wo])),this.w2=tl(aa([wo,Jo],-t,t)),this.b2=tl(On([Jo]))}forward(e){return le(()=>{const t=e.reshape([1,bi]),s=Nc(t.matMul(this.w1).add(this.b1)),r=s.matMul(this.w2).add(this.b2),i=np(r).reshape([Jo]),o=s.reshape([wo]);return{probs:er(i),activations:{kind:"mlp",hidden:er(o)}}})}logProb(e,t){const s=e.reshape([1,bi]),i=Nc(s.matMul(this.w1).add(this.b1)).matMul(this.w2).add(this.b2);return fm(i.reshape([Jo])).gather(Ht(t,"int32"))}params(){return[this.w1,this.b1,this.w2,this.b2]}dispose(){this.params().forEach(e=>e.dispose())}}const Xo=Jo,ui=8,p0=.1;class _me{W;B;constructor(){const e=bi,t=Xo,s=ui,r=Math.sqrt(1/e);this.W=tl(aa([t,s+1,e],-r,r));const i=Tt([t,s+1],"float32");for(let o=0;o=0;h--){const d=a.slice([0,h],[t,1]).reshape([t]),p=this.saferecip(l[h+1]);l[h]=d.add(p)}const c=Ji(l,1);return{logits:l[0],A:a,V:c}}forward(e){return le(()=>{const{logits:t,A:s,V:r}=this.ladderLogits(e),i=np(t);return{probs:er(i),activations:{kind:"cofrnet",A:er(s),V:er(r)}}})}logProb(e,t){const{logits:s}=this.ladderLogits(e);return fm(s).gather(Ht(t,"int32")).reshape([])}params(){return[this.W,this.B]}dispose(){this.params().forEach(e=>e.dispose())}}class uS{constructor(e,t={}){this.net=e,this.opt=Wa.adam(t.lr??.003),this.gamma=t.gamma??.99}buffer=[];opt;gamma;lastLoss=0;episodes=0;startEpisode(){this.buffer.forEach(e=>e.obs.dispose()),this.buffer=[]}record(e,t){this.buffer.push({obs:e.clone(),action:t,reward:0})}completeReward(e){this.buffer.length!==0&&(this.buffer[this.buffer.length-1].reward=e)}endEpisode(){if(this.buffer.length===0)return;const e=new Array(this.buffer.length);let t=0;for(let r=this.buffer.length-1;r>=0;r--)t=this.buffer[r].reward+this.gamma*t,e[r]=t;const s=this.opt.minimize(()=>{let r=Ht(0);for(let i=0;ir.obs.dispose()),this.buffer=[],this.episodes+=1}}class Tme{canvas;ctx;constructor(e){this.canvas=document.createElement("canvas"),e.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d");const t=()=>{const s=window.devicePixelRatio||1;this.canvas.width=e.clientWidth*s,this.canvas.height=e.clientHeight*s,this.ctx.setTransform(s,0,0,s,0,0)};t(),window.addEventListener("resize",t)}setVisible(e){this.canvas.style.display=e?"block":"none"}draw(e){const t=this.canvas.clientWidth,s=this.canvas.clientHeight,r=this.ctx;r.fillStyle="#0a0a0f",r.fillRect(0,0,t,s);const i=t*.12,o=t*.5,a=t*.88,l=C1(bi,i,s,1),c=C1(wo,o,s,8),u=C1(Jo,a,s,1);for(let h=0;h=0?`rgba(130, 255, 180, ${l})`:`rgba(255, 130, 180, ${l})`,n.beginPath(),n.arc(e[r][0],e[r][1],a,0,Math.PI*2),n.fill()}}const Ime=["x","y","vx","vy","plat1.dx","plat1.y","plat1.w","plat2.dx","plat2.y","plat2.w","plat3.dx","plat3.y","plat3.w","plat4.dx","plat4.y","plat4.w","gap1.dx","gap1.w","gap2.dx","gap2.w","gap3.dx","gap3.w","gap4.dx","gap4.w"],T1=[{spine:"#8090b0",glow:"#b8c6e0",bright:"#d0dcf0",negative:"#a070a0"},{spine:"#e86a6a",glow:"#ff9a9a",bright:"#ffc0c0",negative:"#a08080"},{spine:"#68d090",glow:"#98ecb0",bright:"#c4f6d0",negative:"#80a080"},{spine:"#e8b060",glow:"#ffd090",bright:"#ffe4b0",negative:"#a89080"}];function Eme(n){return n/(n*n+p0*p0)}class kme{canvas;ctx;sA;sV;sProbs;phase=0;constructor(e){this.canvas=document.createElement("canvas"),Object.assign(this.canvas.style,{position:"absolute",inset:"0",display:"none",width:"100%",height:"100%"}),e.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d");const t=()=>{const r=window.devicePixelRatio||1;this.canvas.width=e.clientWidth*r,this.canvas.height=e.clientHeight*r,this.ctx.setTransform(r,0,0,r,0,0)};t(),window.addEventListener("resize",t);const s=Xo*(ui+1);this.sA=new Float32Array(s),this.sV=new Float32Array(s),this.sProbs=new Float32Array(Xo)}setVisible(e){this.canvas.style.display=e?"block":"none"}draw(e){const{obs:t,A:s,V:r,W:i,probs:o,argmax:a}=e,l=this.canvas.clientWidth,c=this.canvas.clientHeight,u=this.ctx,h=.28;for(let b=0;b=0?c.spine:c.negative;u&&x>.08&&(e.fillStyle=c.glow,e.globalAlpha=.18*x,e.beginPath(),e.arc(h,p,m*2.8,0,Math.PI*2),e.fill(),e.globalAlpha=1),e.fillStyle=v,e.globalAlpha=.42+.58*x,e.beginPath(),e.arc(h,p,m,0,Math.PI*2),e.fill(),e.globalAlpha=1,l===0&&(e.fillStyle="#3b4456",e.textAlign="right",e.textBaseline="middle",e.font="9px ui-monospace, Menlo, Consolas, monospace",e.fillText(`k=${d}`,h-m-4,p))}if(u){const d=this.sA[l*(ui+1)+0];e.fillStyle=c.bright,e.textAlign="left",e.textBaseline="middle",e.font="10px ui-monospace, Menlo, Consolas, monospace",e.fillText(`a₀=${d.toFixed(2)}`,h+14,r)}}}drawFooter(e,t,s,r,i,o,a){const l=T1[a],c=Rx[a]??"?";e.fillStyle="#1a1d28",e.fillRect(0,s-6,t,1);const u=a*(ui+1)*bi+0*bi,h=[];for(let w=0;wC.value-w.value);const d=h.slice(0,5),p=Math.max(1e-6,...d.map(w=>w.value)),f=12;let x=s+2;e.fillStyle="#9aa8c0",e.font="11px ui-monospace, Menlo, Consolas, monospace",e.textAlign="left",e.textBaseline="top",e.fillText("why ",f,x),e.fillStyle=l.bright,e.font="600 11px ui-monospace, Menlo, Consolas, monospace",e.fillText(c,f+28,x),e.fillStyle="#5e6b7f",e.font="11px ui-monospace, Menlo, Consolas, monospace",e.fillText("? top features × weights at output rung",f+28+e.measureText(c).width,x),x+=18;const m=21,v=f+84+6,y=Math.max(40,t-v-48-f);for(let w=0;w=0?l.spine:l.negative,e.globalAlpha=.85,e.fillRect(v,T-1,E,14),e.globalAlpha=1,e.fillStyle="#8a97af",e.textAlign="right",e.fillText(C.value.toFixed(3),t-f,T)}}}class Ame{canvas;ctx;rewards=[];losses=[];label;constructor(e,t){const s=document.createElement("div");s.style.cssText="display:flex; gap:12px; align-items:center; margin-bottom:4px; font-size:12px; flex-wrap:wrap;";const r=document.createElement("select");for(const[c,u]of[["mlp","MLP"],["cofrnet","CoFrNet"]]){const h=document.createElement("option");h.value=c,h.textContent=u,r.appendChild(h)}r.onchange=()=>t.onArchChange(r.value);const i=document.createElement("input");i.type="number",i.value="1",i.style.width="72px";const o=document.createElement("button");o.textContent="Reset",o.onclick=()=>t.onReset(parseInt(i.value,10)|0);const a=document.createElement("button");a.textContent="Pause",a.onclick=()=>{const c=t.onTogglePause();a.textContent=c?"Play":"Pause"},this.label=document.createElement("span"),this.label.style.marginLeft="auto",s.append(hS("brain:"),r,hS("seed:"),i,o,a,this.label),e.appendChild(s),this.canvas=document.createElement("canvas"),this.canvas.style.cssText="width:100%; height:80px;",e.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d");const l=()=>{const c=window.devicePixelRatio||1;this.canvas.width=this.canvas.clientWidth*c,this.canvas.height=this.canvas.clientHeight*c,this.ctx.setTransform(c,0,0,c,0,0)};l(),window.addEventListener("resize",l)}pushEpisodeReward(e){this.rewards.push(e),this.rewards.length>300&&this.rewards.shift()}pushLoss(e){this.losses.push(e),this.losses.length>300&&this.losses.shift()}setStatus(e){this.label.textContent=e}draw(){const e=this.canvas.clientWidth,t=this.canvas.clientHeight,s=this.ctx;s.fillStyle="#0a0a0f",s.fillRect(0,0,e,t),dS(s,0,0,e/2-4,t,this.rewards,"#66ffcc","episode reward"),dS(s,e/2+4,0,e/2-4,t,this.losses,"#ffcc66","loss / update")}}function hS(n){const e=document.createElement("span");return e.textContent=n,e.style.color="#888",e}function dS(n,e,t,s,r,i,o,a){if(n.strokeStyle="#222",n.strokeRect(e+.5,t+.5,s-1,r-1),n.fillStyle="#888",n.font="10px ui-monospace",n.fillText(a,e+6,t+12),i.length<2)return;const l=Math.min(...i),c=Math.max(...i),u=Math.max(1e-6,c-l);n.strokeStyle=o,n.lineWidth=1,n.beginPath();for(let h=0;h15?c="…"+a.slice(r-15,r):c=a.slice(0,r);var u;i+15n.replace(Rme,"-$1").toLowerCase(),Mme={"&":"&",">":">","<":"<",'"':""","'":"'"},Nme=/[&><"']/g,Bs=n=>String(n).replace(Nme,e=>Mme[e]),Ef=n=>n.type==="ordgroup"||n.type==="color"?n.body.length===1?Ef(n.body[0]):n:n.type==="font"?Ef(n.body):n,$me=new Set(["mathord","textord","atom"]),Po=n=>$me.has(Ef(n).type),Dme=n=>{var e=/^[\x00-\x20]*([^\\/#?]*?)(:|�*58|�*3a|&colon)/i.exec(n);return e?e[2]!==":"||!/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(e[1])?null:e[1].toLowerCase():"_relative"},Ux={displayMode:{type:"boolean",description:"Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.",cli:"-d, --display-mode"},output:{type:{enum:["htmlAndMathml","html","mathml"]},description:"Determines the markup language of the output.",cli:"-F, --format "},leqno:{type:"boolean",description:"Render display math in leqno style (left-justified tags)."},fleqn:{type:"boolean",description:"Render display math flush left."},throwOnError:{type:"boolean",default:!0,cli:"-t, --no-throw-on-error",cliDescription:"Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error."},errorColor:{type:"string",default:"#cc0000",cli:"-c, --error-color ",cliDescription:"A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.",cliProcessor:n=>"#"+n},macros:{type:"object",cli:"-m, --macro ",cliDescription:"Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).",cliDefault:[],cliProcessor:(n,e)=>(e.push(n),e)},minRuleThickness:{type:"number",description:"Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",processor:n=>Math.max(0,n),cli:"--min-rule-thickness ",cliProcessor:parseFloat},colorIsTextColor:{type:"boolean",description:"Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.",cli:"-b, --color-is-text-color"},strict:{type:[{enum:["warn","ignore","error"]},"boolean","function"],description:"Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.",cli:"-S, --strict",cliDefault:!1},trust:{type:["boolean","function"],description:"Trust the input, enabling all HTML features such as \\url.",cli:"-T, --trust"},maxSize:{type:"number",default:1/0,description:"If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large",processor:n=>Math.max(0,n),cli:"-s, --max-size ",cliProcessor:parseInt},maxExpand:{type:"number",default:1e3,description:"Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.",processor:n=>Math.max(0,n),cli:"-e, --max-expand ",cliProcessor:n=>n==="Infinity"?1/0:parseInt(n)},globalGroup:{type:"boolean",cli:!1}};function Pme(n){if("default"in n)return n.default;var e=n.type,t=Array.isArray(e)?e[0]:e;if(typeof t!="string")return t.enum[0];switch(t){case"boolean":return!1;case"string":return"";case"number":return 0;case"object":return{}}}class fb{constructor(e){e===void 0&&(e={}),e=e||{};for(var t of Object.keys(Ux)){var s=Ux[t],r=e[t];this[t]=r!==void 0?s.processor?s.processor(r):r:Pme(s)}}reportNonstrict(e,t,s){var r=this.strict;if(typeof r=="function"&&(r=r(e,t,s)),!(!r||r==="ignore")){if(r===!0||r==="error")throw new Ae("LaTeX-incompatible input and strict mode is set to 'error': "+(t+" ["+e+"]"),s);r==="warn"?typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+(t+" ["+e+"]")):typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to "+("unrecognized '"+r+"': "+t+" ["+e+"]"))}}useStrictBehavior(e,t,s){var r=this.strict;if(typeof r=="function")try{r=r(e,t,s)}catch{r="error"}return!r||r==="ignore"?!1:r===!0||r==="error"?!0:r==="warn"?(typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+(t+" ["+e+"]")),!1):(typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to "+("unrecognized '"+r+"': "+t+" ["+e+"]")),!1)}isTrusted(e){if("url"in e&&e.url&&!e.protocol){var t=Dme(e.url);if(t==null)return!1;e.protocol=t}var s=typeof this.trust=="function"?this.trust(e):this.trust;return!!s}}class Go{constructor(e,t,s){this.id=e,this.size=t,this.cramped=s}sup(){return zi[Lme[this.id]]}sub(){return zi[Fme[this.id]]}fracNum(){return zi[Ome[this.id]]}fracDen(){return zi[zme[this.id]]}cramp(){return zi[Bme[this.id]]}text(){return zi[Ume[this.id]]}isTight(){return this.size>=2}}var mb=0,f0=1,Ec=2,Eo=3,Qh=4,Qr=5,Hc=6,Qs=7,zi=[new Go(mb,0,!1),new Go(f0,0,!0),new Go(Ec,1,!1),new Go(Eo,1,!0),new Go(Qh,2,!1),new Go(Qr,2,!0),new Go(Hc,3,!1),new Go(Qs,3,!0)],Lme=[Qh,Qr,Qh,Qr,Hc,Qs,Hc,Qs],Fme=[Qr,Qr,Qr,Qr,Qs,Qs,Qs,Qs],Ome=[Ec,Eo,Qh,Qr,Hc,Qs,Hc,Qs],zme=[Eo,Eo,Qr,Qr,Qs,Qs,Qs,Qs],Bme=[f0,f0,Eo,Eo,Qr,Qr,Qs,Qs],Ume=[mb,f0,Ec,Eo,Ec,Eo,Ec,Eo],kt={DISPLAY:zi[mb],TEXT:zi[Ec],SCRIPT:zi[Qh],SCRIPTSCRIPT:zi[Hc]},Vx=[{name:"latin",blocks:[[256,591],[768,879]]},{name:"cyrillic",blocks:[[1024,1279]]},{name:"armenian",blocks:[[1328,1423]]},{name:"brahmic",blocks:[[2304,4255]]},{name:"georgian",blocks:[[4256,4351]]},{name:"cjk",blocks:[[12288,12543],[19968,40879],[65280,65376]]},{name:"hangul",blocks:[[44032,55215]]}];function Vme(n){for(var e=0;e=r[0]&&n<=r[1])return t.name}return null}var kf=[];Vx.forEach(n=>n.blocks.forEach(e=>kf.push(...e)));function gA(n){for(var e=0;e=kf[e]&&n<=kf[e+1])return!0;return!1}var as=n=>n+" "+n,pc=80,Wme=function(e,t){return"M95,"+(622+e+t)+` +c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14 +c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54 +c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10 +s173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429 +c69,-144,104.5,-217.7,106.5,-221 +l`+e/2.075+" -"+e+` +c5.3,-9.3,12,-14,20,-14 +H400000v`+(40+e)+`H845.2724 +s-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7 +c-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z +M`+(834+e)+" "+t+"h400000v"+(40+e)+"h-400000z"},Gme=function(e,t){return"M263,"+(601+e+t)+`c0.7,0,18,39.7,52,119 +c34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120 +c340,-704.7,510.7,-1060.3,512,-1067 +l`+e/2.084+" -"+e+` +c4.7,-7.3,11,-11,19,-11 +H40000v`+(40+e)+`H1012.3 +s-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,232 +c-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1 +s-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26 +c-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z +M`+(1001+e)+" "+t+"h400000v"+(40+e)+"h-400000z"},Hme=function(e,t){return"M983 "+(10+e+t)+` +l`+e/3.13+" -"+e+` +c4,-6.7,10,-10,18,-10 H400000v`+(40+e)+` +H1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7 +s-12,0,-12,0c-1.3,-3.3,-3.7,-11.7,-7,-25c-35.3,-125.3,-106.7,-373.3,-214,-744 +c-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30 +c26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722 +c56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5 +c53.7,-170.3,84.5,-266.8,92.5,-289.5z +M`+(1001+e)+" "+t+"h400000v"+(40+e)+"h-400000z"},qme=function(e,t){return"M424,"+(2398+e+t)+` +c-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514 +c0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20 +s-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121 +s209,968,209,968c0,-2,84.7,-361.7,254,-1079c169.3,-717.3,254.7,-1077.7,256,-1081 +l`+e/4.223+" -"+e+`c4,-6.7,10,-10,18,-10 H400000 +v`+(40+e)+`H1014.6 +s-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185 +c-2,6,-10,9,-24,9 +c-8,0,-12,-0.7,-12,-2z M`+(1001+e)+" "+t+` +h400000v`+(40+e)+"h-400000z"},Xme=function(e,t){return"M473,"+(2713+e+t)+` +c339.3,-1799.3,509.3,-2700,510,-2702 l`+e/5.298+" -"+e+` +c3.3,-7.3,9.3,-11,18,-11 H400000v`+(40+e)+`H1017.7 +s-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9 +c-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200 +c0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26 +s76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104, +606zM`+(1001+e)+" "+t+"h400000v"+(40+e)+"H1017.7z"},Kme=function(e){var t=e/2;return"M400000 "+e+" H0 L"+t+" 0 l65 45 L145 "+(e-80)+" H400000z"},jme=function(e,t,s){var r=s-54-t-e;return"M702 "+(e+t)+"H400000"+(40+e)+` +H742v`+r+`l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1 +h-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170 +c-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667 +219 661 l218 661zM702 `+t+"H400000v"+(40+e)+"H742z"},Yme=function(e,t,s){t=1e3*t;var r="";switch(e){case"sqrtMain":r=Wme(t,pc);break;case"sqrtSize1":r=Gme(t,pc);break;case"sqrtSize2":r=Hme(t,pc);break;case"sqrtSize3":r=qme(t,pc);break;case"sqrtSize4":r=Xme(t,pc);break;case"sqrtTall":r=jme(t,pc,s)}return r},Zme=function(e,t){switch(e){case"⎜":return as("M291 0 H417 V"+t+" H291z");case"∣":return as("M145 0 H188 V"+t+" H145z");case"∥":return as("M145 0 H188 V"+t+" H145z")+as("M367 0 H410 V"+t+" H367z");case"⎟":return as("M457 0 H583 V"+t+" H457z");case"⎢":return as("M319 0 H403 V"+t+" H319z");case"⎥":return as("M263 0 H347 V"+t+" H263z");case"⎪":return as("M384 0 H504 V"+t+" H384z");case"⏐":return as("M312 0 H355 V"+t+" H312z");case"‖":return as("M257 0 H300 V"+t+" H257z")+as("M478 0 H521 V"+t+" H478z");default:return""}},pS={doubleleftarrow:`M262 157 +l10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3 + 0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28 + 14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5 +c2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5 + 157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87 +-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7 +-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z +m8 0v40h399730v-40zm0 194v40h399730v-40z`,doublerightarrow:`M399738 392l +-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5 + 14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88 +-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68 +-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18 +-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782 +c-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3 +-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z`,leftarrow:`M400000 241H110l3-3c68.7-52.7 113.7-120 + 135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8 +-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247 +c-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208 + 490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3 + 1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202 + l-3-3h399890zM100 241v40h399900v-40z`,leftbrace:`M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117 +-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7 + 5-6 9-10 13-.7 1-7.3 1-20 1H6z`,leftbraceunder:`M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13 + 35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688 + 0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7 +-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z`,leftgroup:`M400000 80 +H435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0 + 435 0h399565z`,leftgroupunder:`M400000 262 +H435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219 + 435 219h399565z`,leftharpoon:`M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3 +-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5 +-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7 +-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z`,leftharpoonplus:`M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5 + 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3 +-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7 +-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z +m0 0v40h400000v-40z`,leftharpoondown:`M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333 + 5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5 + 1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667 +-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z`,leftharpoondownplus:`M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12 + 10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7 +-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0 +v40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z`,lefthook:`M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5 +-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3 +-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21 + 71.5 23h399859zM103 281v-40h399897v40z`,leftlinesegment:as("M40 281 V428 H0 V94 H40 V241 H400000 v40z"),leftbracketunder:as("M0 0 h120 V290 H399995 v120 H0z"),leftbracketover:as("M0 440 h120 V150 H399995 v-120 H0z"),leftmapsto:as("M40 281 V448H0V74H40V241H400000v40z"),leftToFrom:`M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23 +-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8 +c28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3 + 68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,longequal:as("M0 50 h400000 v40H0z m0 194h40000v40H0z"),midbrace:`M200428 334 +c-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14 +-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7 + 311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11 + 12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z`,midbraceunder:`M199572 214 +c100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14 + 53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3 + 11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0 +-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z`,oiintSize1:`M512.6 71.6c272.6 0 320.3 106.8 320.3 178.2 0 70.8-47.7 177.6 +-320.3 177.6S193.1 320.6 193.1 249.8c0-71.4 46.9-178.2 319.5-178.2z +m368.1 178.2c0-86.4-60.9-215.4-368.1-215.4-306.4 0-367.3 129-367.3 215.4 0 85.8 +60.9 214.8 367.3 214.8 307.2 0 368.1-129 368.1-214.8z`,oiintSize2:`M757.8 100.1c384.7 0 451.1 137.6 451.1 230 0 91.3-66.4 228.8 +-451.1 228.8-386.3 0-452.7-137.5-452.7-228.8 0-92.4 66.4-230 452.7-230z +m502.4 230c0-111.2-82.4-277.2-502.4-277.2s-504 166-504 277.2 +c0 110 84 276 504 276s502.4-166 502.4-276z`,oiiintSize1:`M681.4 71.6c408.9 0 480.5 106.8 480.5 178.2 0 70.8-71.6 177.6 +-480.5 177.6S202.1 320.6 202.1 249.8c0-71.4 70.5-178.2 479.3-178.2z +m525.8 178.2c0-86.4-86.8-215.4-525.7-215.4-437.9 0-524.7 129-524.7 215.4 0 +85.8 86.8 214.8 524.7 214.8 438.9 0 525.7-129 525.7-214.8z`,oiiintSize2:`M1021.2 53c603.6 0 707.8 165.8 707.8 277.2 0 110-104.2 275.8 +-707.8 275.8-606 0-710.2-165.8-710.2-275.8C311 218.8 415.2 53 1021.2 53z +m770.4 277.1c0-131.2-126.4-327.6-770.5-327.6S248.4 198.9 248.4 330.1 +c0 130 128.8 326.4 772.7 326.4s770.5-196.4 770.5-326.4z`,rightarrow:`M0 241v40h399891c-47.3 35.3-84 78-110 128 +-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 + 11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 + 39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85 +-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5 +-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67 + 151.7 139 205zm0 0v40h399900v-40z`,rightbrace:`M400000 542l +-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5 +s-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1 +c124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z`,rightbraceunder:`M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3 + 28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237 +-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z`,rightgroup:`M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0 + 3-1 3-3v-38c-76-158-257-219-435-219H0z`,rightgroupunder:`M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18 + 0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z`,rightharpoon:`M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3 +-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2 +-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 + 69.2 92 94.5zm0 0v40h399900v-40z`,rightharpoonplus:`M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11 +-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7 + 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z +m0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z`,rightharpoondown:`M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8 + 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5 +-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95 +-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z`,rightharpoondownplus:`M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8 + 15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 + 8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3 +-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z +m0-194v40h400000v-40zm0 0v40h400000v-40z`,righthook:`M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3 + 15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0 +-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21 + 66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z`,rightlinesegment:as("M399960 241 V94 h40 V428 h-40 V281 H0 v-40z"),rightbracketunder:as("M399995 0 h-120 V290 H0 v120 H400000z"),rightbracketover:as("M399995 440 h-120 V150 H0 v-120 H399995z"),rightToFrom:`M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23 + 1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32 +-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142 +-167z M100 147v40h399900v-40zM0 341v40h399900v-40z`,twoheadleftarrow:`M0 167c68 40 + 115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69 +-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3 +-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19 +-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101 + 10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z`,twoheadrightarrow:`M400000 167 +c-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3 + 41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42 + 18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333 +-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70 + 101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z`,tilde1:`M200 55.538c-77 0-168 73.953-177 73.953-3 0-7 +-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0 + 114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0 + 4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128 +-68.267.847-113-73.952-191-73.952z`,tilde2:`M344 55.266c-142 0-300.638 81.316-311.5 86.418 +-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9 + 31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114 +c1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751 + 181.476 676 181.476c-149 0-189-126.21-332-126.21z`,tilde3:`M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457 +-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0 + 411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697 + 16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696 + -338 0-409-156.573-744-156.573z`,tilde4:`M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345 +-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409 + 177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9 + 14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409 + -175.236-744-175.236z`,vec:`M377 20c0-5.333 1.833-10 5.5-14S391 0 397 0c4.667 0 8.667 1.667 12 5 +3.333 2.667 6.667 9 10 19 6.667 24.667 20.333 43.667 41 57 7.333 4.667 11 +10.667 11 18 0 6-1 10-3 12s-6.667 5-14 9c-28.667 14.667-53.667 35.667-75 63 +-1.333 1.333-3.167 3.5-5.5 6.5s-4 4.833-5 5.5c-1 .667-2.5 1.333-4.5 2s-4.333 1 +-7 1c-4.667 0-9.167-1.833-13.5-5.5S337 184 337 178c0-12.667 15.667-32.333 47-59 +H213l-171-1c-8.667-6-13-12.333-13-19 0-4.667 4.333-11.333 13-20h359 +c-16-25.333-24-45-24-59z`,widehat1:`M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22 +c-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z`,widehat2:`M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10 +-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widehat3:`M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10 +-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widehat4:`M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10 +-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widecheck1:`M529,159h5l519,-115c5,-1,9,-5,9,-10c0,-1,-1,-2,-1,-3l-4,-22c-1, +-5,-5,-9,-11,-9h-2l-512,92l-513,-92h-2c-5,0,-9,4,-11,9l-5,22c-1,6,2,12,8,13z`,widecheck2:`M1181,220h2l1171,-176c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10, +-11,-10h-1l-1168,153l-1167,-153h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,widecheck3:`M1181,280h2l1171,-236c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10, +-11,-10h-1l-1168,213l-1167,-213h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,widecheck4:`M1181,340h2l1171,-296c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10, +-11,-10h-1l-1168,273l-1167,-273h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,baraboveleftarrow:`M400000 620h-399890l3 -3c68.7 -52.7 113.7 -120 135 -202 +c4 -14.7 6 -23 6 -25c0 -7.3 -7 -11 -21 -11c-8 0 -13.2 0.8 -15.5 2.5 +c-2.3 1.7 -4.2 5.8 -5.5 12.5c-1.3 4.7 -2.7 10.3 -4 17c-12 48.7 -34.8 92 -68.5 130 +s-74.2 66.3 -121.5 85c-10 4 -16 7.7 -18 11c0 8.7 6 14.3 18 17c47.3 18.7 87.8 47 +121.5 85s56.5 81.3 68.5 130c0.7 2 1.3 5 2 9s1.2 6.7 1.5 8c0.3 1.3 1 3.3 2 6 +s2.2 4.5 3.5 5.5c1.3 1 3.3 1.8 6 2.5s6 1 10 1c14 0 21 -3.7 21 -11 +c0 -2 -2 -10.3 -6 -25c-20 -79.3 -65 -146.7 -135 -202l-3 -3h399890z +M100 620v40h399900v-40z M0 241v40h399900v-40zM0 241v40h399900v-40z`,rightarrowabovebar:`M0 241v40h399891c-47.3 35.3-84 78-110 128-16.7 32 +-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 11 8 0 +13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 39 +-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85-40.5 +-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5 +-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67 +151.7 139 205zm96 379h399894v40H0zm0 0h399904v40H0z`,baraboveshortleftharpoon:`M507,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11 +c1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17 +c2,0.7,5,1,9,1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21 +c-32,-87.3,-82.7,-157.7,-152,-211c0,0,-3,-3,-3,-3l399351,0l0,-40 +c-398570,0,-399437,0,-399437,0z M593 435 v40 H399500 v-40z +M0 281 v-40 H399908 v40z M0 281 v-40 H399908 v40z`,rightharpoonaboveshortbar:`M0,241 l0,40c399126,0,399993,0,399993,0 +c4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199, +-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6 +c-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z +M0 241 v40 H399908 v-40z M0 475 v-40 H399500 v40z M0 475 v-40 H399500 v40z`,shortbaraboveleftharpoon:`M7,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11 +c1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17c2,0.7,5,1,9, +1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21c-32,-87.3,-82.7,-157.7, +-152,-211c0,0,-3,-3,-3,-3l399907,0l0,-40c-399126,0,-399993,0,-399993,0z +M93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z`,shortrightharpoonabovebar:`M53,241l0,40c398570,0,399437,0,399437,0 +c4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199, +-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6 +c-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z +M500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z`},Jme=function(e,t){switch(e){case"lbrack":return"M403 1759 V84 H666 V0 H319 V1759 v"+t+` v1759 h347 v-84 +H403z M403 1759 V0 H319 V1759 v`+t+" v1759 h84z";case"rbrack":return"M347 1759 V0 H0 V84 H263 V1759 v"+t+` v1759 H0 v84 H347z +M347 1759 V0 H263 V1759 v`+t+" v1759 h84z";case"vert":return"M145 15 v585 v"+t+` v585 c2.667,10,9.667,15,21,15 +c10,0,16.667,-5,20,-15 v-585 v`+-t+` v-585 c-2.667,-10,-9.667,-15,-21,-15 +c-10,0,-16.667,5,-20,15z M188 15 H145 v585 v`+t+" v585 h43z";case"doublevert":return"M145 15 v585 v"+t+` v585 c2.667,10,9.667,15,21,15 +c10,0,16.667,-5,20,-15 v-585 v`+-t+` v-585 c-2.667,-10,-9.667,-15,-21,-15 +c-10,0,-16.667,5,-20,15z M188 15 H145 v585 v`+t+` v585 h43z +M367 15 v585 v`+t+` v585 c2.667,10,9.667,15,21,15 +c10,0,16.667,-5,20,-15 v-585 v`+-t+` v-585 c-2.667,-10,-9.667,-15,-21,-15 +c-10,0,-16.667,5,-20,15z M410 15 H367 v585 v`+t+" v585 h43z";case"lfloor":return"M319 602 V0 H403 V602 v"+t+` v1715 h263 v84 H319z +MM319 602 V0 H403 V602 v`+t+" v1715 H319z";case"rfloor":return"M319 602 V0 H403 V602 v"+t+` v1799 H0 v-84 H319z +MM319 602 V0 H403 V602 v`+t+" v1715 H319z";case"lceil":return"M403 1759 V84 H666 V0 H319 V1759 v"+t+` v602 h84z +M403 1759 V0 H319 V1759 v`+t+" v602 h84z";case"rceil":return"M347 1759 V0 H0 V84 H263 V1759 v"+t+` v602 h84z +M347 1759 V0 h-84 V1759 v`+t+" v602 h84z";case"lparen":return`M863,9c0,-2,-2,-5,-6,-9c0,0,-17,0,-17,0c-12.7,0,-19.3,0.3,-20,1 +c-5.3,5.3,-10.3,11,-15,17c-242.7,294.7,-395.3,682,-458,1162c-21.3,163.3,-33.3,349, +-36,557 l0,`+(t+84)+`c0.2,6,0,26,0,60c2,159.3,10,310.7,24,454c53.3,528,210, +949.7,470,1265c4.7,6,9.7,11.7,15,17c0.7,0.7,7,1,19,1c0,0,18,0,18,0c4,-4,6,-7,6,-9 +c0,-2.7,-3.3,-8.7,-10,-18c-135.3,-192.7,-235.5,-414.3,-300.5,-665c-65,-250.7,-102.5, +-544.7,-112.5,-882c-2,-104,-3,-167,-3,-189 +l0,-`+(t+92)+`c0,-162.7,5.7,-314,17,-454c20.7,-272,63.7,-513,129,-723c65.3, +-210,155.3,-396.3,270,-559c6.7,-9.3,10,-15.3,10,-18z`;case"rparen":return`M76,0c-16.7,0,-25,3,-25,9c0,2,2,6.3,6,13c21.3,28.7,42.3,60.3, +63,95c96.7,156.7,172.8,332.5,228.5,527.5c55.7,195,92.8,416.5,111.5,664.5 +c11.3,139.3,17,290.7,17,454c0,28,1.7,43,3.3,45l0,`+(t+9)+` +c-3,4,-3.3,16.7,-3.3,38c0,162,-5.7,313.7,-17,455c-18.7,248,-55.8,469.3,-111.5,664 +c-55.7,194.7,-131.8,370.3,-228.5,527c-20.7,34.7,-41.7,66.3,-63,95c-2,3.3,-4,7,-6,11 +c0,7.3,5.7,11,17,11c0,0,11,0,11,0c9.3,0,14.3,-0.3,15,-1c5.3,-5.3,10.3,-11,15,-17 +c242.7,-294.7,395.3,-681.7,458,-1161c21.3,-164.7,33.3,-350.7,36,-558 +l0,-`+(t+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7, +-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z`;default:throw new Error("Unknown stretchy delimiter.")}};class lh{constructor(e){this.children=e,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(e){return this.classes.includes(e)}toNode(){for(var e=document.createDocumentFragment(),t=0;tt.toText();return this.children.map(e).join("")}}var Wx={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:803/800,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:803/800},Qme={ex:!0,em:!0,mu:!0},xA=function(e){return typeof e!="string"&&(e=e.unit),e in Wx||e in Qme||e==="ex"},Dn=function(e,t){var s;if(e.unit in Wx)s=Wx[e.unit]/t.fontMetrics().ptPerEm/t.sizeMultiplier;else if(e.unit==="mu")s=t.fontMetrics().cssEmPerMu;else{var r;if(t.style.isTight()?r=t.havingStyle(t.style.text()):r=t,e.unit==="ex")s=r.fontMetrics().xHeight;else if(e.unit==="em")s=r.fontMetrics().quad;else throw new Ae("Invalid unit: '"+e.unit+"'");r!==t&&(s*=r.sizeMultiplier/t.sizeMultiplier)}return Math.min(e.number*s,t.maxSize)},Ne=function(e){return+e.toFixed(4)+"em"},ma=function(e){return e.filter(t=>t).join(" ")},vA=function(e,t,s){if(this.classes=e||[],this.attributes={},this.height=0,this.depth=0,this.maxFontSize=0,this.style=s||{},t){t.style.isTight()&&this.classes.push("mtight");var r=t.getColor();r&&(this.style.color=r)}},bA=function(e){var t=document.createElement(e);t.className=ma(this.classes);for(var s of Object.keys(this.style))t.style[s]=this.style[s];for(var r of Object.keys(this.attributes))t.setAttribute(r,this.attributes[r]);for(var i=0;i/=\x00-\x1f]/,yA=function(e){var t="<"+e;this.classes.length&&(t+=' class="'+Bs(ma(this.classes))+'"');var s="";for(var r of Object.keys(this.style))s+=pb(r)+":"+this.style[r]+";";s&&(t+=' style="'+Bs(s)+'"');for(var i of Object.keys(this.attributes)){if(ege.test(i))throw new Ae("Invalid attribute name '"+i+"'");t+=" "+i+'="'+Bs(this.attributes[i])+'"'}t+=">";for(var o=0;o",t};class ch{constructor(e,t,s,r){vA.call(this,e,s,r),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return bA.call(this,"span")}toMarkup(){return yA.call(this,"span")}}class cg{constructor(e,t,s,r){vA.call(this,t,r),this.children=s||[],this.setAttribute("href",e)}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return bA.call(this,"a")}toMarkup(){return yA.call(this,"a")}}class tge{constructor(e,t,s){this.alt=t,this.src=e,this.classes=["mord"],this.height=0,this.depth=0,this.maxFontSize=0,this.style=s}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createElement("img");e.src=this.src,e.alt=this.alt,e.className="mord";for(var t of Object.keys(this.style))e.style[t]=this.style[t];return e}toMarkup(){var e=''+Bs(this.alt)+'0&&(t=document.createElement("span"),t.style.marginRight=Ne(this.italic)),this.classes.length>0&&(t=t||document.createElement("span"),t.className=ma(this.classes));for(var s of Object.keys(this.style))t=t||document.createElement("span"),t.style[s]=this.style[s];return t?(t.appendChild(e),t):e}toMarkup(){var e=!1,t="0&&(s+="margin-right:"+Ne(this.italic)+";");for(var r of Object.keys(this.style))s+=pb(r)+":"+this.style[r]+";";s&&(e=!0,t+=' style="'+Bs(s)+'"');var i=Bs(this.text);return e?(t+=">",t+=i,t+="",t):i}}class Mo{constructor(e,t){this.children=e||[],this.attributes=t||{}}toNode(){var e="http://www.w3.org/2000/svg",t=document.createElementNS(e,"svg");for(var s of Object.keys(this.attributes))t.setAttribute(s,this.attributes[s]);for(var r=0;r':''}}class Gx{constructor(e){this.attributes=e||{}}toNode(){var e="http://www.w3.org/2000/svg",t=document.createElementNS(e,"line");for(var s of Object.keys(this.attributes))t.setAttribute(s,this.attributes[s]);return t}toMarkup(){var e=" but got "+String(n)+".")}var ige=n=>n instanceof ch||n instanceof cg||n instanceof lh,Wi={"AMS-Regular":{32:[0,0,0,0,.25],65:[0,.68889,0,0,.72222],66:[0,.68889,0,0,.66667],67:[0,.68889,0,0,.72222],68:[0,.68889,0,0,.72222],69:[0,.68889,0,0,.66667],70:[0,.68889,0,0,.61111],71:[0,.68889,0,0,.77778],72:[0,.68889,0,0,.77778],73:[0,.68889,0,0,.38889],74:[.16667,.68889,0,0,.5],75:[0,.68889,0,0,.77778],76:[0,.68889,0,0,.66667],77:[0,.68889,0,0,.94445],78:[0,.68889,0,0,.72222],79:[.16667,.68889,0,0,.77778],80:[0,.68889,0,0,.61111],81:[.16667,.68889,0,0,.77778],82:[0,.68889,0,0,.72222],83:[0,.68889,0,0,.55556],84:[0,.68889,0,0,.66667],85:[0,.68889,0,0,.72222],86:[0,.68889,0,0,.72222],87:[0,.68889,0,0,1],88:[0,.68889,0,0,.72222],89:[0,.68889,0,0,.72222],90:[0,.68889,0,0,.66667],107:[0,.68889,0,0,.55556],160:[0,0,0,0,.25],165:[0,.675,.025,0,.75],174:[.15559,.69224,0,0,.94666],240:[0,.68889,0,0,.55556],295:[0,.68889,0,0,.54028],710:[0,.825,0,0,2.33334],732:[0,.9,0,0,2.33334],770:[0,.825,0,0,2.33334],771:[0,.9,0,0,2.33334],989:[.08167,.58167,0,0,.77778],1008:[0,.43056,.04028,0,.66667],8245:[0,.54986,0,0,.275],8463:[0,.68889,0,0,.54028],8487:[0,.68889,0,0,.72222],8498:[0,.68889,0,0,.55556],8502:[0,.68889,0,0,.66667],8503:[0,.68889,0,0,.44445],8504:[0,.68889,0,0,.66667],8513:[0,.68889,0,0,.63889],8592:[-.03598,.46402,0,0,.5],8594:[-.03598,.46402,0,0,.5],8602:[-.13313,.36687,0,0,1],8603:[-.13313,.36687,0,0,1],8606:[.01354,.52239,0,0,1],8608:[.01354,.52239,0,0,1],8610:[.01354,.52239,0,0,1.11111],8611:[.01354,.52239,0,0,1.11111],8619:[0,.54986,0,0,1],8620:[0,.54986,0,0,1],8621:[-.13313,.37788,0,0,1.38889],8622:[-.13313,.36687,0,0,1],8624:[0,.69224,0,0,.5],8625:[0,.69224,0,0,.5],8630:[0,.43056,0,0,1],8631:[0,.43056,0,0,1],8634:[.08198,.58198,0,0,.77778],8635:[.08198,.58198,0,0,.77778],8638:[.19444,.69224,0,0,.41667],8639:[.19444,.69224,0,0,.41667],8642:[.19444,.69224,0,0,.41667],8643:[.19444,.69224,0,0,.41667],8644:[.1808,.675,0,0,1],8646:[.1808,.675,0,0,1],8647:[.1808,.675,0,0,1],8648:[.19444,.69224,0,0,.83334],8649:[.1808,.675,0,0,1],8650:[.19444,.69224,0,0,.83334],8651:[.01354,.52239,0,0,1],8652:[.01354,.52239,0,0,1],8653:[-.13313,.36687,0,0,1],8654:[-.13313,.36687,0,0,1],8655:[-.13313,.36687,0,0,1],8666:[.13667,.63667,0,0,1],8667:[.13667,.63667,0,0,1],8669:[-.13313,.37788,0,0,1],8672:[-.064,.437,0,0,1.334],8674:[-.064,.437,0,0,1.334],8705:[0,.825,0,0,.5],8708:[0,.68889,0,0,.55556],8709:[.08167,.58167,0,0,.77778],8717:[0,.43056,0,0,.42917],8722:[-.03598,.46402,0,0,.5],8724:[.08198,.69224,0,0,.77778],8726:[.08167,.58167,0,0,.77778],8733:[0,.69224,0,0,.77778],8736:[0,.69224,0,0,.72222],8737:[0,.69224,0,0,.72222],8738:[.03517,.52239,0,0,.72222],8739:[.08167,.58167,0,0,.22222],8740:[.25142,.74111,0,0,.27778],8741:[.08167,.58167,0,0,.38889],8742:[.25142,.74111,0,0,.5],8756:[0,.69224,0,0,.66667],8757:[0,.69224,0,0,.66667],8764:[-.13313,.36687,0,0,.77778],8765:[-.13313,.37788,0,0,.77778],8769:[-.13313,.36687,0,0,.77778],8770:[-.03625,.46375,0,0,.77778],8774:[.30274,.79383,0,0,.77778],8776:[-.01688,.48312,0,0,.77778],8778:[.08167,.58167,0,0,.77778],8782:[.06062,.54986,0,0,.77778],8783:[.06062,.54986,0,0,.77778],8785:[.08198,.58198,0,0,.77778],8786:[.08198,.58198,0,0,.77778],8787:[.08198,.58198,0,0,.77778],8790:[0,.69224,0,0,.77778],8791:[.22958,.72958,0,0,.77778],8796:[.08198,.91667,0,0,.77778],8806:[.25583,.75583,0,0,.77778],8807:[.25583,.75583,0,0,.77778],8808:[.25142,.75726,0,0,.77778],8809:[.25142,.75726,0,0,.77778],8812:[.25583,.75583,0,0,.5],8814:[.20576,.70576,0,0,.77778],8815:[.20576,.70576,0,0,.77778],8816:[.30274,.79383,0,0,.77778],8817:[.30274,.79383,0,0,.77778],8818:[.22958,.72958,0,0,.77778],8819:[.22958,.72958,0,0,.77778],8822:[.1808,.675,0,0,.77778],8823:[.1808,.675,0,0,.77778],8828:[.13667,.63667,0,0,.77778],8829:[.13667,.63667,0,0,.77778],8830:[.22958,.72958,0,0,.77778],8831:[.22958,.72958,0,0,.77778],8832:[.20576,.70576,0,0,.77778],8833:[.20576,.70576,0,0,.77778],8840:[.30274,.79383,0,0,.77778],8841:[.30274,.79383,0,0,.77778],8842:[.13597,.63597,0,0,.77778],8843:[.13597,.63597,0,0,.77778],8847:[.03517,.54986,0,0,.77778],8848:[.03517,.54986,0,0,.77778],8858:[.08198,.58198,0,0,.77778],8859:[.08198,.58198,0,0,.77778],8861:[.08198,.58198,0,0,.77778],8862:[0,.675,0,0,.77778],8863:[0,.675,0,0,.77778],8864:[0,.675,0,0,.77778],8865:[0,.675,0,0,.77778],8872:[0,.69224,0,0,.61111],8873:[0,.69224,0,0,.72222],8874:[0,.69224,0,0,.88889],8876:[0,.68889,0,0,.61111],8877:[0,.68889,0,0,.61111],8878:[0,.68889,0,0,.72222],8879:[0,.68889,0,0,.72222],8882:[.03517,.54986,0,0,.77778],8883:[.03517,.54986,0,0,.77778],8884:[.13667,.63667,0,0,.77778],8885:[.13667,.63667,0,0,.77778],8888:[0,.54986,0,0,1.11111],8890:[.19444,.43056,0,0,.55556],8891:[.19444,.69224,0,0,.61111],8892:[.19444,.69224,0,0,.61111],8901:[0,.54986,0,0,.27778],8903:[.08167,.58167,0,0,.77778],8905:[.08167,.58167,0,0,.77778],8906:[.08167,.58167,0,0,.77778],8907:[0,.69224,0,0,.77778],8908:[0,.69224,0,0,.77778],8909:[-.03598,.46402,0,0,.77778],8910:[0,.54986,0,0,.76042],8911:[0,.54986,0,0,.76042],8912:[.03517,.54986,0,0,.77778],8913:[.03517,.54986,0,0,.77778],8914:[0,.54986,0,0,.66667],8915:[0,.54986,0,0,.66667],8916:[0,.69224,0,0,.66667],8918:[.0391,.5391,0,0,.77778],8919:[.0391,.5391,0,0,.77778],8920:[.03517,.54986,0,0,1.33334],8921:[.03517,.54986,0,0,1.33334],8922:[.38569,.88569,0,0,.77778],8923:[.38569,.88569,0,0,.77778],8926:[.13667,.63667,0,0,.77778],8927:[.13667,.63667,0,0,.77778],8928:[.30274,.79383,0,0,.77778],8929:[.30274,.79383,0,0,.77778],8934:[.23222,.74111,0,0,.77778],8935:[.23222,.74111,0,0,.77778],8936:[.23222,.74111,0,0,.77778],8937:[.23222,.74111,0,0,.77778],8938:[.20576,.70576,0,0,.77778],8939:[.20576,.70576,0,0,.77778],8940:[.30274,.79383,0,0,.77778],8941:[.30274,.79383,0,0,.77778],8994:[.19444,.69224,0,0,.77778],8995:[.19444,.69224,0,0,.77778],9416:[.15559,.69224,0,0,.90222],9484:[0,.69224,0,0,.5],9488:[0,.69224,0,0,.5],9492:[0,.37788,0,0,.5],9496:[0,.37788,0,0,.5],9585:[.19444,.68889,0,0,.88889],9586:[.19444,.74111,0,0,.88889],9632:[0,.675,0,0,.77778],9633:[0,.675,0,0,.77778],9650:[0,.54986,0,0,.72222],9651:[0,.54986,0,0,.72222],9654:[.03517,.54986,0,0,.77778],9660:[0,.54986,0,0,.72222],9661:[0,.54986,0,0,.72222],9664:[.03517,.54986,0,0,.77778],9674:[.11111,.69224,0,0,.66667],9733:[.19444,.69224,0,0,.94445],10003:[0,.69224,0,0,.83334],10016:[0,.69224,0,0,.83334],10731:[.11111,.69224,0,0,.66667],10846:[.19444,.75583,0,0,.61111],10877:[.13667,.63667,0,0,.77778],10878:[.13667,.63667,0,0,.77778],10885:[.25583,.75583,0,0,.77778],10886:[.25583,.75583,0,0,.77778],10887:[.13597,.63597,0,0,.77778],10888:[.13597,.63597,0,0,.77778],10889:[.26167,.75726,0,0,.77778],10890:[.26167,.75726,0,0,.77778],10891:[.48256,.98256,0,0,.77778],10892:[.48256,.98256,0,0,.77778],10901:[.13667,.63667,0,0,.77778],10902:[.13667,.63667,0,0,.77778],10933:[.25142,.75726,0,0,.77778],10934:[.25142,.75726,0,0,.77778],10935:[.26167,.75726,0,0,.77778],10936:[.26167,.75726,0,0,.77778],10937:[.26167,.75726,0,0,.77778],10938:[.26167,.75726,0,0,.77778],10949:[.25583,.75583,0,0,.77778],10950:[.25583,.75583,0,0,.77778],10955:[.28481,.79383,0,0,.77778],10956:[.28481,.79383,0,0,.77778],57350:[.08167,.58167,0,0,.22222],57351:[.08167,.58167,0,0,.38889],57352:[.08167,.58167,0,0,.77778],57353:[0,.43056,.04028,0,.66667],57356:[.25142,.75726,0,0,.77778],57357:[.25142,.75726,0,0,.77778],57358:[.41951,.91951,0,0,.77778],57359:[.30274,.79383,0,0,.77778],57360:[.30274,.79383,0,0,.77778],57361:[.41951,.91951,0,0,.77778],57366:[.25142,.75726,0,0,.77778],57367:[.25142,.75726,0,0,.77778],57368:[.25142,.75726,0,0,.77778],57369:[.25142,.75726,0,0,.77778],57370:[.13597,.63597,0,0,.77778],57371:[.13597,.63597,0,0,.77778]},"Caligraphic-Regular":{32:[0,0,0,0,.25],65:[0,.68333,0,.19445,.79847],66:[0,.68333,.03041,.13889,.65681],67:[0,.68333,.05834,.13889,.52653],68:[0,.68333,.02778,.08334,.77139],69:[0,.68333,.08944,.11111,.52778],70:[0,.68333,.09931,.11111,.71875],71:[.09722,.68333,.0593,.11111,.59487],72:[0,.68333,.00965,.11111,.84452],73:[0,.68333,.07382,0,.54452],74:[.09722,.68333,.18472,.16667,.67778],75:[0,.68333,.01445,.05556,.76195],76:[0,.68333,0,.13889,.68972],77:[0,.68333,0,.13889,1.2009],78:[0,.68333,.14736,.08334,.82049],79:[0,.68333,.02778,.11111,.79611],80:[0,.68333,.08222,.08334,.69556],81:[.09722,.68333,0,.11111,.81667],82:[0,.68333,0,.08334,.8475],83:[0,.68333,.075,.13889,.60556],84:[0,.68333,.25417,0,.54464],85:[0,.68333,.09931,.08334,.62583],86:[0,.68333,.08222,0,.61278],87:[0,.68333,.08222,.08334,.98778],88:[0,.68333,.14643,.13889,.7133],89:[.09722,.68333,.08222,.08334,.66834],90:[0,.68333,.07944,.13889,.72473],160:[0,0,0,0,.25]},"Fraktur-Regular":{32:[0,0,0,0,.25],33:[0,.69141,0,0,.29574],34:[0,.69141,0,0,.21471],38:[0,.69141,0,0,.73786],39:[0,.69141,0,0,.21201],40:[.24982,.74947,0,0,.38865],41:[.24982,.74947,0,0,.38865],42:[0,.62119,0,0,.27764],43:[.08319,.58283,0,0,.75623],44:[0,.10803,0,0,.27764],45:[.08319,.58283,0,0,.75623],46:[0,.10803,0,0,.27764],47:[.24982,.74947,0,0,.50181],48:[0,.47534,0,0,.50181],49:[0,.47534,0,0,.50181],50:[0,.47534,0,0,.50181],51:[.18906,.47534,0,0,.50181],52:[.18906,.47534,0,0,.50181],53:[.18906,.47534,0,0,.50181],54:[0,.69141,0,0,.50181],55:[.18906,.47534,0,0,.50181],56:[0,.69141,0,0,.50181],57:[.18906,.47534,0,0,.50181],58:[0,.47534,0,0,.21606],59:[.12604,.47534,0,0,.21606],61:[-.13099,.36866,0,0,.75623],63:[0,.69141,0,0,.36245],65:[0,.69141,0,0,.7176],66:[0,.69141,0,0,.88397],67:[0,.69141,0,0,.61254],68:[0,.69141,0,0,.83158],69:[0,.69141,0,0,.66278],70:[.12604,.69141,0,0,.61119],71:[0,.69141,0,0,.78539],72:[.06302,.69141,0,0,.7203],73:[0,.69141,0,0,.55448],74:[.12604,.69141,0,0,.55231],75:[0,.69141,0,0,.66845],76:[0,.69141,0,0,.66602],77:[0,.69141,0,0,1.04953],78:[0,.69141,0,0,.83212],79:[0,.69141,0,0,.82699],80:[.18906,.69141,0,0,.82753],81:[.03781,.69141,0,0,.82699],82:[0,.69141,0,0,.82807],83:[0,.69141,0,0,.82861],84:[0,.69141,0,0,.66899],85:[0,.69141,0,0,.64576],86:[0,.69141,0,0,.83131],87:[0,.69141,0,0,1.04602],88:[0,.69141,0,0,.71922],89:[.18906,.69141,0,0,.83293],90:[.12604,.69141,0,0,.60201],91:[.24982,.74947,0,0,.27764],93:[.24982,.74947,0,0,.27764],94:[0,.69141,0,0,.49965],97:[0,.47534,0,0,.50046],98:[0,.69141,0,0,.51315],99:[0,.47534,0,0,.38946],100:[0,.62119,0,0,.49857],101:[0,.47534,0,0,.40053],102:[.18906,.69141,0,0,.32626],103:[.18906,.47534,0,0,.5037],104:[.18906,.69141,0,0,.52126],105:[0,.69141,0,0,.27899],106:[0,.69141,0,0,.28088],107:[0,.69141,0,0,.38946],108:[0,.69141,0,0,.27953],109:[0,.47534,0,0,.76676],110:[0,.47534,0,0,.52666],111:[0,.47534,0,0,.48885],112:[.18906,.52396,0,0,.50046],113:[.18906,.47534,0,0,.48912],114:[0,.47534,0,0,.38919],115:[0,.47534,0,0,.44266],116:[0,.62119,0,0,.33301],117:[0,.47534,0,0,.5172],118:[0,.52396,0,0,.5118],119:[0,.52396,0,0,.77351],120:[.18906,.47534,0,0,.38865],121:[.18906,.47534,0,0,.49884],122:[.18906,.47534,0,0,.39054],160:[0,0,0,0,.25],8216:[0,.69141,0,0,.21471],8217:[0,.69141,0,0,.21471],58112:[0,.62119,0,0,.49749],58113:[0,.62119,0,0,.4983],58114:[.18906,.69141,0,0,.33328],58115:[.18906,.69141,0,0,.32923],58116:[.18906,.47534,0,0,.50343],58117:[0,.69141,0,0,.33301],58118:[0,.62119,0,0,.33409],58119:[0,.47534,0,0,.50073]},"Main-Bold":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.35],34:[0,.69444,0,0,.60278],35:[.19444,.69444,0,0,.95833],36:[.05556,.75,0,0,.575],37:[.05556,.75,0,0,.95833],38:[0,.69444,0,0,.89444],39:[0,.69444,0,0,.31944],40:[.25,.75,0,0,.44722],41:[.25,.75,0,0,.44722],42:[0,.75,0,0,.575],43:[.13333,.63333,0,0,.89444],44:[.19444,.15556,0,0,.31944],45:[0,.44444,0,0,.38333],46:[0,.15556,0,0,.31944],47:[.25,.75,0,0,.575],48:[0,.64444,0,0,.575],49:[0,.64444,0,0,.575],50:[0,.64444,0,0,.575],51:[0,.64444,0,0,.575],52:[0,.64444,0,0,.575],53:[0,.64444,0,0,.575],54:[0,.64444,0,0,.575],55:[0,.64444,0,0,.575],56:[0,.64444,0,0,.575],57:[0,.64444,0,0,.575],58:[0,.44444,0,0,.31944],59:[.19444,.44444,0,0,.31944],60:[.08556,.58556,0,0,.89444],61:[-.10889,.39111,0,0,.89444],62:[.08556,.58556,0,0,.89444],63:[0,.69444,0,0,.54305],64:[0,.69444,0,0,.89444],65:[0,.68611,0,0,.86944],66:[0,.68611,0,0,.81805],67:[0,.68611,0,0,.83055],68:[0,.68611,0,0,.88194],69:[0,.68611,0,0,.75555],70:[0,.68611,0,0,.72361],71:[0,.68611,0,0,.90416],72:[0,.68611,0,0,.9],73:[0,.68611,0,0,.43611],74:[0,.68611,0,0,.59444],75:[0,.68611,0,0,.90138],76:[0,.68611,0,0,.69166],77:[0,.68611,0,0,1.09166],78:[0,.68611,0,0,.9],79:[0,.68611,0,0,.86388],80:[0,.68611,0,0,.78611],81:[.19444,.68611,0,0,.86388],82:[0,.68611,0,0,.8625],83:[0,.68611,0,0,.63889],84:[0,.68611,0,0,.8],85:[0,.68611,0,0,.88472],86:[0,.68611,.01597,0,.86944],87:[0,.68611,.01597,0,1.18888],88:[0,.68611,0,0,.86944],89:[0,.68611,.02875,0,.86944],90:[0,.68611,0,0,.70277],91:[.25,.75,0,0,.31944],92:[.25,.75,0,0,.575],93:[.25,.75,0,0,.31944],94:[0,.69444,0,0,.575],95:[.31,.13444,.03194,0,.575],97:[0,.44444,0,0,.55902],98:[0,.69444,0,0,.63889],99:[0,.44444,0,0,.51111],100:[0,.69444,0,0,.63889],101:[0,.44444,0,0,.52708],102:[0,.69444,.10903,0,.35139],103:[.19444,.44444,.01597,0,.575],104:[0,.69444,0,0,.63889],105:[0,.69444,0,0,.31944],106:[.19444,.69444,0,0,.35139],107:[0,.69444,0,0,.60694],108:[0,.69444,0,0,.31944],109:[0,.44444,0,0,.95833],110:[0,.44444,0,0,.63889],111:[0,.44444,0,0,.575],112:[.19444,.44444,0,0,.63889],113:[.19444,.44444,0,0,.60694],114:[0,.44444,0,0,.47361],115:[0,.44444,0,0,.45361],116:[0,.63492,0,0,.44722],117:[0,.44444,0,0,.63889],118:[0,.44444,.01597,0,.60694],119:[0,.44444,.01597,0,.83055],120:[0,.44444,0,0,.60694],121:[.19444,.44444,.01597,0,.60694],122:[0,.44444,0,0,.51111],123:[.25,.75,0,0,.575],124:[.25,.75,0,0,.31944],125:[.25,.75,0,0,.575],126:[.35,.34444,0,0,.575],160:[0,0,0,0,.25],163:[0,.69444,0,0,.86853],168:[0,.69444,0,0,.575],172:[0,.44444,0,0,.76666],176:[0,.69444,0,0,.86944],177:[.13333,.63333,0,0,.89444],184:[.17014,0,0,0,.51111],198:[0,.68611,0,0,1.04166],215:[.13333,.63333,0,0,.89444],216:[.04861,.73472,0,0,.89444],223:[0,.69444,0,0,.59722],230:[0,.44444,0,0,.83055],247:[.13333,.63333,0,0,.89444],248:[.09722,.54167,0,0,.575],305:[0,.44444,0,0,.31944],338:[0,.68611,0,0,1.16944],339:[0,.44444,0,0,.89444],567:[.19444,.44444,0,0,.35139],710:[0,.69444,0,0,.575],711:[0,.63194,0,0,.575],713:[0,.59611,0,0,.575],714:[0,.69444,0,0,.575],715:[0,.69444,0,0,.575],728:[0,.69444,0,0,.575],729:[0,.69444,0,0,.31944],730:[0,.69444,0,0,.86944],732:[0,.69444,0,0,.575],733:[0,.69444,0,0,.575],915:[0,.68611,0,0,.69166],916:[0,.68611,0,0,.95833],920:[0,.68611,0,0,.89444],923:[0,.68611,0,0,.80555],926:[0,.68611,0,0,.76666],928:[0,.68611,0,0,.9],931:[0,.68611,0,0,.83055],933:[0,.68611,0,0,.89444],934:[0,.68611,0,0,.83055],936:[0,.68611,0,0,.89444],937:[0,.68611,0,0,.83055],8211:[0,.44444,.03194,0,.575],8212:[0,.44444,.03194,0,1.14999],8216:[0,.69444,0,0,.31944],8217:[0,.69444,0,0,.31944],8220:[0,.69444,0,0,.60278],8221:[0,.69444,0,0,.60278],8224:[.19444,.69444,0,0,.51111],8225:[.19444,.69444,0,0,.51111],8242:[0,.55556,0,0,.34444],8407:[0,.72444,.15486,0,.575],8463:[0,.69444,0,0,.66759],8465:[0,.69444,0,0,.83055],8467:[0,.69444,0,0,.47361],8472:[.19444,.44444,0,0,.74027],8476:[0,.69444,0,0,.83055],8501:[0,.69444,0,0,.70277],8592:[-.10889,.39111,0,0,1.14999],8593:[.19444,.69444,0,0,.575],8594:[-.10889,.39111,0,0,1.14999],8595:[.19444,.69444,0,0,.575],8596:[-.10889,.39111,0,0,1.14999],8597:[.25,.75,0,0,.575],8598:[.19444,.69444,0,0,1.14999],8599:[.19444,.69444,0,0,1.14999],8600:[.19444,.69444,0,0,1.14999],8601:[.19444,.69444,0,0,1.14999],8636:[-.10889,.39111,0,0,1.14999],8637:[-.10889,.39111,0,0,1.14999],8640:[-.10889,.39111,0,0,1.14999],8641:[-.10889,.39111,0,0,1.14999],8656:[-.10889,.39111,0,0,1.14999],8657:[.19444,.69444,0,0,.70277],8658:[-.10889,.39111,0,0,1.14999],8659:[.19444,.69444,0,0,.70277],8660:[-.10889,.39111,0,0,1.14999],8661:[.25,.75,0,0,.70277],8704:[0,.69444,0,0,.63889],8706:[0,.69444,.06389,0,.62847],8707:[0,.69444,0,0,.63889],8709:[.05556,.75,0,0,.575],8711:[0,.68611,0,0,.95833],8712:[.08556,.58556,0,0,.76666],8715:[.08556,.58556,0,0,.76666],8722:[.13333,.63333,0,0,.89444],8723:[.13333,.63333,0,0,.89444],8725:[.25,.75,0,0,.575],8726:[.25,.75,0,0,.575],8727:[-.02778,.47222,0,0,.575],8728:[-.02639,.47361,0,0,.575],8729:[-.02639,.47361,0,0,.575],8730:[.18,.82,0,0,.95833],8733:[0,.44444,0,0,.89444],8734:[0,.44444,0,0,1.14999],8736:[0,.69224,0,0,.72222],8739:[.25,.75,0,0,.31944],8741:[.25,.75,0,0,.575],8743:[0,.55556,0,0,.76666],8744:[0,.55556,0,0,.76666],8745:[0,.55556,0,0,.76666],8746:[0,.55556,0,0,.76666],8747:[.19444,.69444,.12778,0,.56875],8764:[-.10889,.39111,0,0,.89444],8768:[.19444,.69444,0,0,.31944],8771:[.00222,.50222,0,0,.89444],8773:[.027,.638,0,0,.894],8776:[.02444,.52444,0,0,.89444],8781:[.00222,.50222,0,0,.89444],8801:[.00222,.50222,0,0,.89444],8804:[.19667,.69667,0,0,.89444],8805:[.19667,.69667,0,0,.89444],8810:[.08556,.58556,0,0,1.14999],8811:[.08556,.58556,0,0,1.14999],8826:[.08556,.58556,0,0,.89444],8827:[.08556,.58556,0,0,.89444],8834:[.08556,.58556,0,0,.89444],8835:[.08556,.58556,0,0,.89444],8838:[.19667,.69667,0,0,.89444],8839:[.19667,.69667,0,0,.89444],8846:[0,.55556,0,0,.76666],8849:[.19667,.69667,0,0,.89444],8850:[.19667,.69667,0,0,.89444],8851:[0,.55556,0,0,.76666],8852:[0,.55556,0,0,.76666],8853:[.13333,.63333,0,0,.89444],8854:[.13333,.63333,0,0,.89444],8855:[.13333,.63333,0,0,.89444],8856:[.13333,.63333,0,0,.89444],8857:[.13333,.63333,0,0,.89444],8866:[0,.69444,0,0,.70277],8867:[0,.69444,0,0,.70277],8868:[0,.69444,0,0,.89444],8869:[0,.69444,0,0,.89444],8900:[-.02639,.47361,0,0,.575],8901:[-.02639,.47361,0,0,.31944],8902:[-.02778,.47222,0,0,.575],8968:[.25,.75,0,0,.51111],8969:[.25,.75,0,0,.51111],8970:[.25,.75,0,0,.51111],8971:[.25,.75,0,0,.51111],8994:[-.13889,.36111,0,0,1.14999],8995:[-.13889,.36111,0,0,1.14999],9651:[.19444,.69444,0,0,1.02222],9657:[-.02778,.47222,0,0,.575],9661:[.19444,.69444,0,0,1.02222],9667:[-.02778,.47222,0,0,.575],9711:[.19444,.69444,0,0,1.14999],9824:[.12963,.69444,0,0,.89444],9825:[.12963,.69444,0,0,.89444],9826:[.12963,.69444,0,0,.89444],9827:[.12963,.69444,0,0,.89444],9837:[0,.75,0,0,.44722],9838:[.19444,.69444,0,0,.44722],9839:[.19444,.69444,0,0,.44722],10216:[.25,.75,0,0,.44722],10217:[.25,.75,0,0,.44722],10815:[0,.68611,0,0,.9],10927:[.19667,.69667,0,0,.89444],10928:[.19667,.69667,0,0,.89444],57376:[.19444,.69444,0,0,0]},"Main-BoldItalic":{32:[0,0,0,0,.25],33:[0,.69444,.11417,0,.38611],34:[0,.69444,.07939,0,.62055],35:[.19444,.69444,.06833,0,.94444],37:[.05556,.75,.12861,0,.94444],38:[0,.69444,.08528,0,.88555],39:[0,.69444,.12945,0,.35555],40:[.25,.75,.15806,0,.47333],41:[.25,.75,.03306,0,.47333],42:[0,.75,.14333,0,.59111],43:[.10333,.60333,.03306,0,.88555],44:[.19444,.14722,0,0,.35555],45:[0,.44444,.02611,0,.41444],46:[0,.14722,0,0,.35555],47:[.25,.75,.15806,0,.59111],48:[0,.64444,.13167,0,.59111],49:[0,.64444,.13167,0,.59111],50:[0,.64444,.13167,0,.59111],51:[0,.64444,.13167,0,.59111],52:[.19444,.64444,.13167,0,.59111],53:[0,.64444,.13167,0,.59111],54:[0,.64444,.13167,0,.59111],55:[.19444,.64444,.13167,0,.59111],56:[0,.64444,.13167,0,.59111],57:[0,.64444,.13167,0,.59111],58:[0,.44444,.06695,0,.35555],59:[.19444,.44444,.06695,0,.35555],61:[-.10889,.39111,.06833,0,.88555],63:[0,.69444,.11472,0,.59111],64:[0,.69444,.09208,0,.88555],65:[0,.68611,0,0,.86555],66:[0,.68611,.0992,0,.81666],67:[0,.68611,.14208,0,.82666],68:[0,.68611,.09062,0,.87555],69:[0,.68611,.11431,0,.75666],70:[0,.68611,.12903,0,.72722],71:[0,.68611,.07347,0,.89527],72:[0,.68611,.17208,0,.8961],73:[0,.68611,.15681,0,.47166],74:[0,.68611,.145,0,.61055],75:[0,.68611,.14208,0,.89499],76:[0,.68611,0,0,.69777],77:[0,.68611,.17208,0,1.07277],78:[0,.68611,.17208,0,.8961],79:[0,.68611,.09062,0,.85499],80:[0,.68611,.0992,0,.78721],81:[.19444,.68611,.09062,0,.85499],82:[0,.68611,.02559,0,.85944],83:[0,.68611,.11264,0,.64999],84:[0,.68611,.12903,0,.7961],85:[0,.68611,.17208,0,.88083],86:[0,.68611,.18625,0,.86555],87:[0,.68611,.18625,0,1.15999],88:[0,.68611,.15681,0,.86555],89:[0,.68611,.19803,0,.86555],90:[0,.68611,.14208,0,.70888],91:[.25,.75,.1875,0,.35611],93:[.25,.75,.09972,0,.35611],94:[0,.69444,.06709,0,.59111],95:[.31,.13444,.09811,0,.59111],97:[0,.44444,.09426,0,.59111],98:[0,.69444,.07861,0,.53222],99:[0,.44444,.05222,0,.53222],100:[0,.69444,.10861,0,.59111],101:[0,.44444,.085,0,.53222],102:[.19444,.69444,.21778,0,.4],103:[.19444,.44444,.105,0,.53222],104:[0,.69444,.09426,0,.59111],105:[0,.69326,.11387,0,.35555],106:[.19444,.69326,.1672,0,.35555],107:[0,.69444,.11111,0,.53222],108:[0,.69444,.10861,0,.29666],109:[0,.44444,.09426,0,.94444],110:[0,.44444,.09426,0,.64999],111:[0,.44444,.07861,0,.59111],112:[.19444,.44444,.07861,0,.59111],113:[.19444,.44444,.105,0,.53222],114:[0,.44444,.11111,0,.50167],115:[0,.44444,.08167,0,.48694],116:[0,.63492,.09639,0,.385],117:[0,.44444,.09426,0,.62055],118:[0,.44444,.11111,0,.53222],119:[0,.44444,.11111,0,.76777],120:[0,.44444,.12583,0,.56055],121:[.19444,.44444,.105,0,.56166],122:[0,.44444,.13889,0,.49055],126:[.35,.34444,.11472,0,.59111],160:[0,0,0,0,.25],168:[0,.69444,.11473,0,.59111],176:[0,.69444,0,0,.94888],184:[.17014,0,0,0,.53222],198:[0,.68611,.11431,0,1.02277],216:[.04861,.73472,.09062,0,.88555],223:[.19444,.69444,.09736,0,.665],230:[0,.44444,.085,0,.82666],248:[.09722,.54167,.09458,0,.59111],305:[0,.44444,.09426,0,.35555],338:[0,.68611,.11431,0,1.14054],339:[0,.44444,.085,0,.82666],567:[.19444,.44444,.04611,0,.385],710:[0,.69444,.06709,0,.59111],711:[0,.63194,.08271,0,.59111],713:[0,.59444,.10444,0,.59111],714:[0,.69444,.08528,0,.59111],715:[0,.69444,0,0,.59111],728:[0,.69444,.10333,0,.59111],729:[0,.69444,.12945,0,.35555],730:[0,.69444,0,0,.94888],732:[0,.69444,.11472,0,.59111],733:[0,.69444,.11472,0,.59111],915:[0,.68611,.12903,0,.69777],916:[0,.68611,0,0,.94444],920:[0,.68611,.09062,0,.88555],923:[0,.68611,0,0,.80666],926:[0,.68611,.15092,0,.76777],928:[0,.68611,.17208,0,.8961],931:[0,.68611,.11431,0,.82666],933:[0,.68611,.10778,0,.88555],934:[0,.68611,.05632,0,.82666],936:[0,.68611,.10778,0,.88555],937:[0,.68611,.0992,0,.82666],8211:[0,.44444,.09811,0,.59111],8212:[0,.44444,.09811,0,1.18221],8216:[0,.69444,.12945,0,.35555],8217:[0,.69444,.12945,0,.35555],8220:[0,.69444,.16772,0,.62055],8221:[0,.69444,.07939,0,.62055]},"Main-Italic":{32:[0,0,0,0,.25],33:[0,.69444,.12417,0,.30667],34:[0,.69444,.06961,0,.51444],35:[.19444,.69444,.06616,0,.81777],37:[.05556,.75,.13639,0,.81777],38:[0,.69444,.09694,0,.76666],39:[0,.69444,.12417,0,.30667],40:[.25,.75,.16194,0,.40889],41:[.25,.75,.03694,0,.40889],42:[0,.75,.14917,0,.51111],43:[.05667,.56167,.03694,0,.76666],44:[.19444,.10556,0,0,.30667],45:[0,.43056,.02826,0,.35778],46:[0,.10556,0,0,.30667],47:[.25,.75,.16194,0,.51111],48:[0,.64444,.13556,0,.51111],49:[0,.64444,.13556,0,.51111],50:[0,.64444,.13556,0,.51111],51:[0,.64444,.13556,0,.51111],52:[.19444,.64444,.13556,0,.51111],53:[0,.64444,.13556,0,.51111],54:[0,.64444,.13556,0,.51111],55:[.19444,.64444,.13556,0,.51111],56:[0,.64444,.13556,0,.51111],57:[0,.64444,.13556,0,.51111],58:[0,.43056,.0582,0,.30667],59:[.19444,.43056,.0582,0,.30667],61:[-.13313,.36687,.06616,0,.76666],63:[0,.69444,.1225,0,.51111],64:[0,.69444,.09597,0,.76666],65:[0,.68333,0,0,.74333],66:[0,.68333,.10257,0,.70389],67:[0,.68333,.14528,0,.71555],68:[0,.68333,.09403,0,.755],69:[0,.68333,.12028,0,.67833],70:[0,.68333,.13305,0,.65277],71:[0,.68333,.08722,0,.77361],72:[0,.68333,.16389,0,.74333],73:[0,.68333,.15806,0,.38555],74:[0,.68333,.14028,0,.525],75:[0,.68333,.14528,0,.76888],76:[0,.68333,0,0,.62722],77:[0,.68333,.16389,0,.89666],78:[0,.68333,.16389,0,.74333],79:[0,.68333,.09403,0,.76666],80:[0,.68333,.10257,0,.67833],81:[.19444,.68333,.09403,0,.76666],82:[0,.68333,.03868,0,.72944],83:[0,.68333,.11972,0,.56222],84:[0,.68333,.13305,0,.71555],85:[0,.68333,.16389,0,.74333],86:[0,.68333,.18361,0,.74333],87:[0,.68333,.18361,0,.99888],88:[0,.68333,.15806,0,.74333],89:[0,.68333,.19383,0,.74333],90:[0,.68333,.14528,0,.61333],91:[.25,.75,.1875,0,.30667],93:[.25,.75,.10528,0,.30667],94:[0,.69444,.06646,0,.51111],95:[.31,.12056,.09208,0,.51111],97:[0,.43056,.07671,0,.51111],98:[0,.69444,.06312,0,.46],99:[0,.43056,.05653,0,.46],100:[0,.69444,.10333,0,.51111],101:[0,.43056,.07514,0,.46],102:[.19444,.69444,.21194,0,.30667],103:[.19444,.43056,.08847,0,.46],104:[0,.69444,.07671,0,.51111],105:[0,.65536,.1019,0,.30667],106:[.19444,.65536,.14467,0,.30667],107:[0,.69444,.10764,0,.46],108:[0,.69444,.10333,0,.25555],109:[0,.43056,.07671,0,.81777],110:[0,.43056,.07671,0,.56222],111:[0,.43056,.06312,0,.51111],112:[.19444,.43056,.06312,0,.51111],113:[.19444,.43056,.08847,0,.46],114:[0,.43056,.10764,0,.42166],115:[0,.43056,.08208,0,.40889],116:[0,.61508,.09486,0,.33222],117:[0,.43056,.07671,0,.53666],118:[0,.43056,.10764,0,.46],119:[0,.43056,.10764,0,.66444],120:[0,.43056,.12042,0,.46389],121:[.19444,.43056,.08847,0,.48555],122:[0,.43056,.12292,0,.40889],126:[.35,.31786,.11585,0,.51111],160:[0,0,0,0,.25],168:[0,.66786,.10474,0,.51111],176:[0,.69444,0,0,.83129],184:[.17014,0,0,0,.46],198:[0,.68333,.12028,0,.88277],216:[.04861,.73194,.09403,0,.76666],223:[.19444,.69444,.10514,0,.53666],230:[0,.43056,.07514,0,.71555],248:[.09722,.52778,.09194,0,.51111],338:[0,.68333,.12028,0,.98499],339:[0,.43056,.07514,0,.71555],710:[0,.69444,.06646,0,.51111],711:[0,.62847,.08295,0,.51111],713:[0,.56167,.10333,0,.51111],714:[0,.69444,.09694,0,.51111],715:[0,.69444,0,0,.51111],728:[0,.69444,.10806,0,.51111],729:[0,.66786,.11752,0,.30667],730:[0,.69444,0,0,.83129],732:[0,.66786,.11585,0,.51111],733:[0,.69444,.1225,0,.51111],915:[0,.68333,.13305,0,.62722],916:[0,.68333,0,0,.81777],920:[0,.68333,.09403,0,.76666],923:[0,.68333,0,0,.69222],926:[0,.68333,.15294,0,.66444],928:[0,.68333,.16389,0,.74333],931:[0,.68333,.12028,0,.71555],933:[0,.68333,.11111,0,.76666],934:[0,.68333,.05986,0,.71555],936:[0,.68333,.11111,0,.76666],937:[0,.68333,.10257,0,.71555],8211:[0,.43056,.09208,0,.51111],8212:[0,.43056,.09208,0,1.02222],8216:[0,.69444,.12417,0,.30667],8217:[0,.69444,.12417,0,.30667],8220:[0,.69444,.1685,0,.51444],8221:[0,.69444,.06961,0,.51444],8463:[0,.68889,0,0,.54028]},"Main-Regular":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.27778],34:[0,.69444,0,0,.5],35:[.19444,.69444,0,0,.83334],36:[.05556,.75,0,0,.5],37:[.05556,.75,0,0,.83334],38:[0,.69444,0,0,.77778],39:[0,.69444,0,0,.27778],40:[.25,.75,0,0,.38889],41:[.25,.75,0,0,.38889],42:[0,.75,0,0,.5],43:[.08333,.58333,0,0,.77778],44:[.19444,.10556,0,0,.27778],45:[0,.43056,0,0,.33333],46:[0,.10556,0,0,.27778],47:[.25,.75,0,0,.5],48:[0,.64444,0,0,.5],49:[0,.64444,0,0,.5],50:[0,.64444,0,0,.5],51:[0,.64444,0,0,.5],52:[0,.64444,0,0,.5],53:[0,.64444,0,0,.5],54:[0,.64444,0,0,.5],55:[0,.64444,0,0,.5],56:[0,.64444,0,0,.5],57:[0,.64444,0,0,.5],58:[0,.43056,0,0,.27778],59:[.19444,.43056,0,0,.27778],60:[.0391,.5391,0,0,.77778],61:[-.13313,.36687,0,0,.77778],62:[.0391,.5391,0,0,.77778],63:[0,.69444,0,0,.47222],64:[0,.69444,0,0,.77778],65:[0,.68333,0,0,.75],66:[0,.68333,0,0,.70834],67:[0,.68333,0,0,.72222],68:[0,.68333,0,0,.76389],69:[0,.68333,0,0,.68056],70:[0,.68333,0,0,.65278],71:[0,.68333,0,0,.78472],72:[0,.68333,0,0,.75],73:[0,.68333,0,0,.36111],74:[0,.68333,0,0,.51389],75:[0,.68333,0,0,.77778],76:[0,.68333,0,0,.625],77:[0,.68333,0,0,.91667],78:[0,.68333,0,0,.75],79:[0,.68333,0,0,.77778],80:[0,.68333,0,0,.68056],81:[.19444,.68333,0,0,.77778],82:[0,.68333,0,0,.73611],83:[0,.68333,0,0,.55556],84:[0,.68333,0,0,.72222],85:[0,.68333,0,0,.75],86:[0,.68333,.01389,0,.75],87:[0,.68333,.01389,0,1.02778],88:[0,.68333,0,0,.75],89:[0,.68333,.025,0,.75],90:[0,.68333,0,0,.61111],91:[.25,.75,0,0,.27778],92:[.25,.75,0,0,.5],93:[.25,.75,0,0,.27778],94:[0,.69444,0,0,.5],95:[.31,.12056,.02778,0,.5],97:[0,.43056,0,0,.5],98:[0,.69444,0,0,.55556],99:[0,.43056,0,0,.44445],100:[0,.69444,0,0,.55556],101:[0,.43056,0,0,.44445],102:[0,.69444,.07778,0,.30556],103:[.19444,.43056,.01389,0,.5],104:[0,.69444,0,0,.55556],105:[0,.66786,0,0,.27778],106:[.19444,.66786,0,0,.30556],107:[0,.69444,0,0,.52778],108:[0,.69444,0,0,.27778],109:[0,.43056,0,0,.83334],110:[0,.43056,0,0,.55556],111:[0,.43056,0,0,.5],112:[.19444,.43056,0,0,.55556],113:[.19444,.43056,0,0,.52778],114:[0,.43056,0,0,.39167],115:[0,.43056,0,0,.39445],116:[0,.61508,0,0,.38889],117:[0,.43056,0,0,.55556],118:[0,.43056,.01389,0,.52778],119:[0,.43056,.01389,0,.72222],120:[0,.43056,0,0,.52778],121:[.19444,.43056,.01389,0,.52778],122:[0,.43056,0,0,.44445],123:[.25,.75,0,0,.5],124:[.25,.75,0,0,.27778],125:[.25,.75,0,0,.5],126:[.35,.31786,0,0,.5],160:[0,0,0,0,.25],163:[0,.69444,0,0,.76909],167:[.19444,.69444,0,0,.44445],168:[0,.66786,0,0,.5],172:[0,.43056,0,0,.66667],176:[0,.69444,0,0,.75],177:[.08333,.58333,0,0,.77778],182:[.19444,.69444,0,0,.61111],184:[.17014,0,0,0,.44445],198:[0,.68333,0,0,.90278],215:[.08333,.58333,0,0,.77778],216:[.04861,.73194,0,0,.77778],223:[0,.69444,0,0,.5],230:[0,.43056,0,0,.72222],247:[.08333,.58333,0,0,.77778],248:[.09722,.52778,0,0,.5],305:[0,.43056,0,0,.27778],338:[0,.68333,0,0,1.01389],339:[0,.43056,0,0,.77778],567:[.19444,.43056,0,0,.30556],710:[0,.69444,0,0,.5],711:[0,.62847,0,0,.5],713:[0,.56778,0,0,.5],714:[0,.69444,0,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,0,0,.5],729:[0,.66786,0,0,.27778],730:[0,.69444,0,0,.75],732:[0,.66786,0,0,.5],733:[0,.69444,0,0,.5],915:[0,.68333,0,0,.625],916:[0,.68333,0,0,.83334],920:[0,.68333,0,0,.77778],923:[0,.68333,0,0,.69445],926:[0,.68333,0,0,.66667],928:[0,.68333,0,0,.75],931:[0,.68333,0,0,.72222],933:[0,.68333,0,0,.77778],934:[0,.68333,0,0,.72222],936:[0,.68333,0,0,.77778],937:[0,.68333,0,0,.72222],8211:[0,.43056,.02778,0,.5],8212:[0,.43056,.02778,0,1],8216:[0,.69444,0,0,.27778],8217:[0,.69444,0,0,.27778],8220:[0,.69444,0,0,.5],8221:[0,.69444,0,0,.5],8224:[.19444,.69444,0,0,.44445],8225:[.19444,.69444,0,0,.44445],8230:[0,.123,0,0,1.172],8242:[0,.55556,0,0,.275],8407:[0,.71444,.15382,0,.5],8463:[0,.68889,0,0,.54028],8465:[0,.69444,0,0,.72222],8467:[0,.69444,0,.11111,.41667],8472:[.19444,.43056,0,.11111,.63646],8476:[0,.69444,0,0,.72222],8501:[0,.69444,0,0,.61111],8592:[-.13313,.36687,0,0,1],8593:[.19444,.69444,0,0,.5],8594:[-.13313,.36687,0,0,1],8595:[.19444,.69444,0,0,.5],8596:[-.13313,.36687,0,0,1],8597:[.25,.75,0,0,.5],8598:[.19444,.69444,0,0,1],8599:[.19444,.69444,0,0,1],8600:[.19444,.69444,0,0,1],8601:[.19444,.69444,0,0,1],8614:[.011,.511,0,0,1],8617:[.011,.511,0,0,1.126],8618:[.011,.511,0,0,1.126],8636:[-.13313,.36687,0,0,1],8637:[-.13313,.36687,0,0,1],8640:[-.13313,.36687,0,0,1],8641:[-.13313,.36687,0,0,1],8652:[.011,.671,0,0,1],8656:[-.13313,.36687,0,0,1],8657:[.19444,.69444,0,0,.61111],8658:[-.13313,.36687,0,0,1],8659:[.19444,.69444,0,0,.61111],8660:[-.13313,.36687,0,0,1],8661:[.25,.75,0,0,.61111],8704:[0,.69444,0,0,.55556],8706:[0,.69444,.05556,.08334,.5309],8707:[0,.69444,0,0,.55556],8709:[.05556,.75,0,0,.5],8711:[0,.68333,0,0,.83334],8712:[.0391,.5391,0,0,.66667],8715:[.0391,.5391,0,0,.66667],8722:[.08333,.58333,0,0,.77778],8723:[.08333,.58333,0,0,.77778],8725:[.25,.75,0,0,.5],8726:[.25,.75,0,0,.5],8727:[-.03472,.46528,0,0,.5],8728:[-.05555,.44445,0,0,.5],8729:[-.05555,.44445,0,0,.5],8730:[.2,.8,0,0,.83334],8733:[0,.43056,0,0,.77778],8734:[0,.43056,0,0,1],8736:[0,.69224,0,0,.72222],8739:[.25,.75,0,0,.27778],8741:[.25,.75,0,0,.5],8743:[0,.55556,0,0,.66667],8744:[0,.55556,0,0,.66667],8745:[0,.55556,0,0,.66667],8746:[0,.55556,0,0,.66667],8747:[.19444,.69444,.11111,0,.41667],8764:[-.13313,.36687,0,0,.77778],8768:[.19444,.69444,0,0,.27778],8771:[-.03625,.46375,0,0,.77778],8773:[-.022,.589,0,0,.778],8776:[-.01688,.48312,0,0,.77778],8781:[-.03625,.46375,0,0,.77778],8784:[-.133,.673,0,0,.778],8801:[-.03625,.46375,0,0,.77778],8804:[.13597,.63597,0,0,.77778],8805:[.13597,.63597,0,0,.77778],8810:[.0391,.5391,0,0,1],8811:[.0391,.5391,0,0,1],8826:[.0391,.5391,0,0,.77778],8827:[.0391,.5391,0,0,.77778],8834:[.0391,.5391,0,0,.77778],8835:[.0391,.5391,0,0,.77778],8838:[.13597,.63597,0,0,.77778],8839:[.13597,.63597,0,0,.77778],8846:[0,.55556,0,0,.66667],8849:[.13597,.63597,0,0,.77778],8850:[.13597,.63597,0,0,.77778],8851:[0,.55556,0,0,.66667],8852:[0,.55556,0,0,.66667],8853:[.08333,.58333,0,0,.77778],8854:[.08333,.58333,0,0,.77778],8855:[.08333,.58333,0,0,.77778],8856:[.08333,.58333,0,0,.77778],8857:[.08333,.58333,0,0,.77778],8866:[0,.69444,0,0,.61111],8867:[0,.69444,0,0,.61111],8868:[0,.69444,0,0,.77778],8869:[0,.69444,0,0,.77778],8872:[.249,.75,0,0,.867],8900:[-.05555,.44445,0,0,.5],8901:[-.05555,.44445,0,0,.27778],8902:[-.03472,.46528,0,0,.5],8904:[.005,.505,0,0,.9],8942:[.03,.903,0,0,.278],8943:[-.19,.313,0,0,1.172],8945:[-.1,.823,0,0,1.282],8968:[.25,.75,0,0,.44445],8969:[.25,.75,0,0,.44445],8970:[.25,.75,0,0,.44445],8971:[.25,.75,0,0,.44445],8994:[-.14236,.35764,0,0,1],8995:[-.14236,.35764,0,0,1],9136:[.244,.744,0,0,.412],9137:[.244,.745,0,0,.412],9651:[.19444,.69444,0,0,.88889],9657:[-.03472,.46528,0,0,.5],9661:[.19444,.69444,0,0,.88889],9667:[-.03472,.46528,0,0,.5],9711:[.19444,.69444,0,0,1],9824:[.12963,.69444,0,0,.77778],9825:[.12963,.69444,0,0,.77778],9826:[.12963,.69444,0,0,.77778],9827:[.12963,.69444,0,0,.77778],9837:[0,.75,0,0,.38889],9838:[.19444,.69444,0,0,.38889],9839:[.19444,.69444,0,0,.38889],10216:[.25,.75,0,0,.38889],10217:[.25,.75,0,0,.38889],10222:[.244,.744,0,0,.412],10223:[.244,.745,0,0,.412],10229:[.011,.511,0,0,1.609],10230:[.011,.511,0,0,1.638],10231:[.011,.511,0,0,1.859],10232:[.024,.525,0,0,1.609],10233:[.024,.525,0,0,1.638],10234:[.024,.525,0,0,1.858],10236:[.011,.511,0,0,1.638],10815:[0,.68333,0,0,.75],10927:[.13597,.63597,0,0,.77778],10928:[.13597,.63597,0,0,.77778],57376:[.19444,.69444,0,0,0]},"Math-BoldItalic":{32:[0,0,0,0,.25],48:[0,.44444,0,0,.575],49:[0,.44444,0,0,.575],50:[0,.44444,0,0,.575],51:[.19444,.44444,0,0,.575],52:[.19444,.44444,0,0,.575],53:[.19444,.44444,0,0,.575],54:[0,.64444,0,0,.575],55:[.19444,.44444,0,0,.575],56:[0,.64444,0,0,.575],57:[.19444,.44444,0,0,.575],65:[0,.68611,0,0,.86944],66:[0,.68611,.04835,0,.8664],67:[0,.68611,.06979,0,.81694],68:[0,.68611,.03194,0,.93812],69:[0,.68611,.05451,0,.81007],70:[0,.68611,.15972,0,.68889],71:[0,.68611,0,0,.88673],72:[0,.68611,.08229,0,.98229],73:[0,.68611,.07778,0,.51111],74:[0,.68611,.10069,0,.63125],75:[0,.68611,.06979,0,.97118],76:[0,.68611,0,0,.75555],77:[0,.68611,.11424,0,1.14201],78:[0,.68611,.11424,0,.95034],79:[0,.68611,.03194,0,.83666],80:[0,.68611,.15972,0,.72309],81:[.19444,.68611,0,0,.86861],82:[0,.68611,.00421,0,.87235],83:[0,.68611,.05382,0,.69271],84:[0,.68611,.15972,0,.63663],85:[0,.68611,.11424,0,.80027],86:[0,.68611,.25555,0,.67778],87:[0,.68611,.15972,0,1.09305],88:[0,.68611,.07778,0,.94722],89:[0,.68611,.25555,0,.67458],90:[0,.68611,.06979,0,.77257],97:[0,.44444,0,0,.63287],98:[0,.69444,0,0,.52083],99:[0,.44444,0,0,.51342],100:[0,.69444,0,0,.60972],101:[0,.44444,0,0,.55361],102:[.19444,.69444,.11042,0,.56806],103:[.19444,.44444,.03704,0,.5449],104:[0,.69444,0,0,.66759],105:[0,.69326,0,0,.4048],106:[.19444,.69326,.0622,0,.47083],107:[0,.69444,.01852,0,.6037],108:[0,.69444,.0088,0,.34815],109:[0,.44444,0,0,1.0324],110:[0,.44444,0,0,.71296],111:[0,.44444,0,0,.58472],112:[.19444,.44444,0,0,.60092],113:[.19444,.44444,.03704,0,.54213],114:[0,.44444,.03194,0,.5287],115:[0,.44444,0,0,.53125],116:[0,.63492,0,0,.41528],117:[0,.44444,0,0,.68102],118:[0,.44444,.03704,0,.56666],119:[0,.44444,.02778,0,.83148],120:[0,.44444,0,0,.65903],121:[.19444,.44444,.03704,0,.59028],122:[0,.44444,.04213,0,.55509],160:[0,0,0,0,.25],915:[0,.68611,.15972,0,.65694],916:[0,.68611,0,0,.95833],920:[0,.68611,.03194,0,.86722],923:[0,.68611,0,0,.80555],926:[0,.68611,.07458,0,.84125],928:[0,.68611,.08229,0,.98229],931:[0,.68611,.05451,0,.88507],933:[0,.68611,.15972,0,.67083],934:[0,.68611,0,0,.76666],936:[0,.68611,.11653,0,.71402],937:[0,.68611,.04835,0,.8789],945:[0,.44444,0,0,.76064],946:[.19444,.69444,.03403,0,.65972],947:[.19444,.44444,.06389,0,.59003],948:[0,.69444,.03819,0,.52222],949:[0,.44444,0,0,.52882],950:[.19444,.69444,.06215,0,.50833],951:[.19444,.44444,.03704,0,.6],952:[0,.69444,.03194,0,.5618],953:[0,.44444,0,0,.41204],954:[0,.44444,0,0,.66759],955:[0,.69444,0,0,.67083],956:[.19444,.44444,0,0,.70787],957:[0,.44444,.06898,0,.57685],958:[.19444,.69444,.03021,0,.50833],959:[0,.44444,0,0,.58472],960:[0,.44444,.03704,0,.68241],961:[.19444,.44444,0,0,.6118],962:[.09722,.44444,.07917,0,.42361],963:[0,.44444,.03704,0,.68588],964:[0,.44444,.13472,0,.52083],965:[0,.44444,.03704,0,.63055],966:[.19444,.44444,0,0,.74722],967:[.19444,.44444,0,0,.71805],968:[.19444,.69444,.03704,0,.75833],969:[0,.44444,.03704,0,.71782],977:[0,.69444,0,0,.69155],981:[.19444,.69444,0,0,.7125],982:[0,.44444,.03194,0,.975],1009:[.19444,.44444,0,0,.6118],1013:[0,.44444,0,0,.48333],57649:[0,.44444,0,0,.39352],57911:[.19444,.44444,0,0,.43889]},"Math-Italic":{32:[0,0,0,0,.25],48:[0,.43056,0,0,.5],49:[0,.43056,0,0,.5],50:[0,.43056,0,0,.5],51:[.19444,.43056,0,0,.5],52:[.19444,.43056,0,0,.5],53:[.19444,.43056,0,0,.5],54:[0,.64444,0,0,.5],55:[.19444,.43056,0,0,.5],56:[0,.64444,0,0,.5],57:[.19444,.43056,0,0,.5],65:[0,.68333,0,.13889,.75],66:[0,.68333,.05017,.08334,.75851],67:[0,.68333,.07153,.08334,.71472],68:[0,.68333,.02778,.05556,.82792],69:[0,.68333,.05764,.08334,.7382],70:[0,.68333,.13889,.08334,.64306],71:[0,.68333,0,.08334,.78625],72:[0,.68333,.08125,.05556,.83125],73:[0,.68333,.07847,.11111,.43958],74:[0,.68333,.09618,.16667,.55451],75:[0,.68333,.07153,.05556,.84931],76:[0,.68333,0,.02778,.68056],77:[0,.68333,.10903,.08334,.97014],78:[0,.68333,.10903,.08334,.80347],79:[0,.68333,.02778,.08334,.76278],80:[0,.68333,.13889,.08334,.64201],81:[.19444,.68333,0,.08334,.79056],82:[0,.68333,.00773,.08334,.75929],83:[0,.68333,.05764,.08334,.6132],84:[0,.68333,.13889,.08334,.58438],85:[0,.68333,.10903,.02778,.68278],86:[0,.68333,.22222,0,.58333],87:[0,.68333,.13889,0,.94445],88:[0,.68333,.07847,.08334,.82847],89:[0,.68333,.22222,0,.58056],90:[0,.68333,.07153,.08334,.68264],97:[0,.43056,0,0,.52859],98:[0,.69444,0,0,.42917],99:[0,.43056,0,.05556,.43276],100:[0,.69444,0,.16667,.52049],101:[0,.43056,0,.05556,.46563],102:[.19444,.69444,.10764,.16667,.48959],103:[.19444,.43056,.03588,.02778,.47697],104:[0,.69444,0,0,.57616],105:[0,.65952,0,0,.34451],106:[.19444,.65952,.05724,0,.41181],107:[0,.69444,.03148,0,.5206],108:[0,.69444,.01968,.08334,.29838],109:[0,.43056,0,0,.87801],110:[0,.43056,0,0,.60023],111:[0,.43056,0,.05556,.48472],112:[.19444,.43056,0,.08334,.50313],113:[.19444,.43056,.03588,.08334,.44641],114:[0,.43056,.02778,.05556,.45116],115:[0,.43056,0,.05556,.46875],116:[0,.61508,0,.08334,.36111],117:[0,.43056,0,.02778,.57246],118:[0,.43056,.03588,.02778,.48472],119:[0,.43056,.02691,.08334,.71592],120:[0,.43056,0,.02778,.57153],121:[.19444,.43056,.03588,.05556,.49028],122:[0,.43056,.04398,.05556,.46505],160:[0,0,0,0,.25],915:[0,.68333,.13889,.08334,.61528],916:[0,.68333,0,.16667,.83334],920:[0,.68333,.02778,.08334,.76278],923:[0,.68333,0,.16667,.69445],926:[0,.68333,.07569,.08334,.74236],928:[0,.68333,.08125,.05556,.83125],931:[0,.68333,.05764,.08334,.77986],933:[0,.68333,.13889,.05556,.58333],934:[0,.68333,0,.08334,.66667],936:[0,.68333,.11,.05556,.61222],937:[0,.68333,.05017,.08334,.7724],945:[0,.43056,.0037,.02778,.6397],946:[.19444,.69444,.05278,.08334,.56563],947:[.19444,.43056,.05556,0,.51773],948:[0,.69444,.03785,.05556,.44444],949:[0,.43056,0,.08334,.46632],950:[.19444,.69444,.07378,.08334,.4375],951:[.19444,.43056,.03588,.05556,.49653],952:[0,.69444,.02778,.08334,.46944],953:[0,.43056,0,.05556,.35394],954:[0,.43056,0,0,.57616],955:[0,.69444,0,0,.58334],956:[.19444,.43056,0,.02778,.60255],957:[0,.43056,.06366,.02778,.49398],958:[.19444,.69444,.04601,.11111,.4375],959:[0,.43056,0,.05556,.48472],960:[0,.43056,.03588,0,.57003],961:[.19444,.43056,0,.08334,.51702],962:[.09722,.43056,.07986,.08334,.36285],963:[0,.43056,.03588,0,.57141],964:[0,.43056,.1132,.02778,.43715],965:[0,.43056,.03588,.02778,.54028],966:[.19444,.43056,0,.08334,.65417],967:[.19444,.43056,0,.05556,.62569],968:[.19444,.69444,.03588,.11111,.65139],969:[0,.43056,.03588,0,.62245],977:[0,.69444,0,.08334,.59144],981:[.19444,.69444,0,.08334,.59583],982:[0,.43056,.02778,0,.82813],1009:[.19444,.43056,0,.08334,.51702],1013:[0,.43056,0,.05556,.4059],57649:[0,.43056,0,.02778,.32246],57911:[.19444,.43056,0,.08334,.38403]},"SansSerif-Bold":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.36667],34:[0,.69444,0,0,.55834],35:[.19444,.69444,0,0,.91667],36:[.05556,.75,0,0,.55],37:[.05556,.75,0,0,1.02912],38:[0,.69444,0,0,.83056],39:[0,.69444,0,0,.30556],40:[.25,.75,0,0,.42778],41:[.25,.75,0,0,.42778],42:[0,.75,0,0,.55],43:[.11667,.61667,0,0,.85556],44:[.10556,.13056,0,0,.30556],45:[0,.45833,0,0,.36667],46:[0,.13056,0,0,.30556],47:[.25,.75,0,0,.55],48:[0,.69444,0,0,.55],49:[0,.69444,0,0,.55],50:[0,.69444,0,0,.55],51:[0,.69444,0,0,.55],52:[0,.69444,0,0,.55],53:[0,.69444,0,0,.55],54:[0,.69444,0,0,.55],55:[0,.69444,0,0,.55],56:[0,.69444,0,0,.55],57:[0,.69444,0,0,.55],58:[0,.45833,0,0,.30556],59:[.10556,.45833,0,0,.30556],61:[-.09375,.40625,0,0,.85556],63:[0,.69444,0,0,.51945],64:[0,.69444,0,0,.73334],65:[0,.69444,0,0,.73334],66:[0,.69444,0,0,.73334],67:[0,.69444,0,0,.70278],68:[0,.69444,0,0,.79445],69:[0,.69444,0,0,.64167],70:[0,.69444,0,0,.61111],71:[0,.69444,0,0,.73334],72:[0,.69444,0,0,.79445],73:[0,.69444,0,0,.33056],74:[0,.69444,0,0,.51945],75:[0,.69444,0,0,.76389],76:[0,.69444,0,0,.58056],77:[0,.69444,0,0,.97778],78:[0,.69444,0,0,.79445],79:[0,.69444,0,0,.79445],80:[0,.69444,0,0,.70278],81:[.10556,.69444,0,0,.79445],82:[0,.69444,0,0,.70278],83:[0,.69444,0,0,.61111],84:[0,.69444,0,0,.73334],85:[0,.69444,0,0,.76389],86:[0,.69444,.01528,0,.73334],87:[0,.69444,.01528,0,1.03889],88:[0,.69444,0,0,.73334],89:[0,.69444,.0275,0,.73334],90:[0,.69444,0,0,.67223],91:[.25,.75,0,0,.34306],93:[.25,.75,0,0,.34306],94:[0,.69444,0,0,.55],95:[.35,.10833,.03056,0,.55],97:[0,.45833,0,0,.525],98:[0,.69444,0,0,.56111],99:[0,.45833,0,0,.48889],100:[0,.69444,0,0,.56111],101:[0,.45833,0,0,.51111],102:[0,.69444,.07639,0,.33611],103:[.19444,.45833,.01528,0,.55],104:[0,.69444,0,0,.56111],105:[0,.69444,0,0,.25556],106:[.19444,.69444,0,0,.28611],107:[0,.69444,0,0,.53056],108:[0,.69444,0,0,.25556],109:[0,.45833,0,0,.86667],110:[0,.45833,0,0,.56111],111:[0,.45833,0,0,.55],112:[.19444,.45833,0,0,.56111],113:[.19444,.45833,0,0,.56111],114:[0,.45833,.01528,0,.37222],115:[0,.45833,0,0,.42167],116:[0,.58929,0,0,.40417],117:[0,.45833,0,0,.56111],118:[0,.45833,.01528,0,.5],119:[0,.45833,.01528,0,.74445],120:[0,.45833,0,0,.5],121:[.19444,.45833,.01528,0,.5],122:[0,.45833,0,0,.47639],126:[.35,.34444,0,0,.55],160:[0,0,0,0,.25],168:[0,.69444,0,0,.55],176:[0,.69444,0,0,.73334],180:[0,.69444,0,0,.55],184:[.17014,0,0,0,.48889],305:[0,.45833,0,0,.25556],567:[.19444,.45833,0,0,.28611],710:[0,.69444,0,0,.55],711:[0,.63542,0,0,.55],713:[0,.63778,0,0,.55],728:[0,.69444,0,0,.55],729:[0,.69444,0,0,.30556],730:[0,.69444,0,0,.73334],732:[0,.69444,0,0,.55],733:[0,.69444,0,0,.55],915:[0,.69444,0,0,.58056],916:[0,.69444,0,0,.91667],920:[0,.69444,0,0,.85556],923:[0,.69444,0,0,.67223],926:[0,.69444,0,0,.73334],928:[0,.69444,0,0,.79445],931:[0,.69444,0,0,.79445],933:[0,.69444,0,0,.85556],934:[0,.69444,0,0,.79445],936:[0,.69444,0,0,.85556],937:[0,.69444,0,0,.79445],8211:[0,.45833,.03056,0,.55],8212:[0,.45833,.03056,0,1.10001],8216:[0,.69444,0,0,.30556],8217:[0,.69444,0,0,.30556],8220:[0,.69444,0,0,.55834],8221:[0,.69444,0,0,.55834]},"SansSerif-Italic":{32:[0,0,0,0,.25],33:[0,.69444,.05733,0,.31945],34:[0,.69444,.00316,0,.5],35:[.19444,.69444,.05087,0,.83334],36:[.05556,.75,.11156,0,.5],37:[.05556,.75,.03126,0,.83334],38:[0,.69444,.03058,0,.75834],39:[0,.69444,.07816,0,.27778],40:[.25,.75,.13164,0,.38889],41:[.25,.75,.02536,0,.38889],42:[0,.75,.11775,0,.5],43:[.08333,.58333,.02536,0,.77778],44:[.125,.08333,0,0,.27778],45:[0,.44444,.01946,0,.33333],46:[0,.08333,0,0,.27778],47:[.25,.75,.13164,0,.5],48:[0,.65556,.11156,0,.5],49:[0,.65556,.11156,0,.5],50:[0,.65556,.11156,0,.5],51:[0,.65556,.11156,0,.5],52:[0,.65556,.11156,0,.5],53:[0,.65556,.11156,0,.5],54:[0,.65556,.11156,0,.5],55:[0,.65556,.11156,0,.5],56:[0,.65556,.11156,0,.5],57:[0,.65556,.11156,0,.5],58:[0,.44444,.02502,0,.27778],59:[.125,.44444,.02502,0,.27778],61:[-.13,.37,.05087,0,.77778],63:[0,.69444,.11809,0,.47222],64:[0,.69444,.07555,0,.66667],65:[0,.69444,0,0,.66667],66:[0,.69444,.08293,0,.66667],67:[0,.69444,.11983,0,.63889],68:[0,.69444,.07555,0,.72223],69:[0,.69444,.11983,0,.59722],70:[0,.69444,.13372,0,.56945],71:[0,.69444,.11983,0,.66667],72:[0,.69444,.08094,0,.70834],73:[0,.69444,.13372,0,.27778],74:[0,.69444,.08094,0,.47222],75:[0,.69444,.11983,0,.69445],76:[0,.69444,0,0,.54167],77:[0,.69444,.08094,0,.875],78:[0,.69444,.08094,0,.70834],79:[0,.69444,.07555,0,.73611],80:[0,.69444,.08293,0,.63889],81:[.125,.69444,.07555,0,.73611],82:[0,.69444,.08293,0,.64584],83:[0,.69444,.09205,0,.55556],84:[0,.69444,.13372,0,.68056],85:[0,.69444,.08094,0,.6875],86:[0,.69444,.1615,0,.66667],87:[0,.69444,.1615,0,.94445],88:[0,.69444,.13372,0,.66667],89:[0,.69444,.17261,0,.66667],90:[0,.69444,.11983,0,.61111],91:[.25,.75,.15942,0,.28889],93:[.25,.75,.08719,0,.28889],94:[0,.69444,.0799,0,.5],95:[.35,.09444,.08616,0,.5],97:[0,.44444,.00981,0,.48056],98:[0,.69444,.03057,0,.51667],99:[0,.44444,.08336,0,.44445],100:[0,.69444,.09483,0,.51667],101:[0,.44444,.06778,0,.44445],102:[0,.69444,.21705,0,.30556],103:[.19444,.44444,.10836,0,.5],104:[0,.69444,.01778,0,.51667],105:[0,.67937,.09718,0,.23889],106:[.19444,.67937,.09162,0,.26667],107:[0,.69444,.08336,0,.48889],108:[0,.69444,.09483,0,.23889],109:[0,.44444,.01778,0,.79445],110:[0,.44444,.01778,0,.51667],111:[0,.44444,.06613,0,.5],112:[.19444,.44444,.0389,0,.51667],113:[.19444,.44444,.04169,0,.51667],114:[0,.44444,.10836,0,.34167],115:[0,.44444,.0778,0,.38333],116:[0,.57143,.07225,0,.36111],117:[0,.44444,.04169,0,.51667],118:[0,.44444,.10836,0,.46111],119:[0,.44444,.10836,0,.68334],120:[0,.44444,.09169,0,.46111],121:[.19444,.44444,.10836,0,.46111],122:[0,.44444,.08752,0,.43472],126:[.35,.32659,.08826,0,.5],160:[0,0,0,0,.25],168:[0,.67937,.06385,0,.5],176:[0,.69444,0,0,.73752],184:[.17014,0,0,0,.44445],305:[0,.44444,.04169,0,.23889],567:[.19444,.44444,.04169,0,.26667],710:[0,.69444,.0799,0,.5],711:[0,.63194,.08432,0,.5],713:[0,.60889,.08776,0,.5],714:[0,.69444,.09205,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,.09483,0,.5],729:[0,.67937,.07774,0,.27778],730:[0,.69444,0,0,.73752],732:[0,.67659,.08826,0,.5],733:[0,.69444,.09205,0,.5],915:[0,.69444,.13372,0,.54167],916:[0,.69444,0,0,.83334],920:[0,.69444,.07555,0,.77778],923:[0,.69444,0,0,.61111],926:[0,.69444,.12816,0,.66667],928:[0,.69444,.08094,0,.70834],931:[0,.69444,.11983,0,.72222],933:[0,.69444,.09031,0,.77778],934:[0,.69444,.04603,0,.72222],936:[0,.69444,.09031,0,.77778],937:[0,.69444,.08293,0,.72222],8211:[0,.44444,.08616,0,.5],8212:[0,.44444,.08616,0,1],8216:[0,.69444,.07816,0,.27778],8217:[0,.69444,.07816,0,.27778],8220:[0,.69444,.14205,0,.5],8221:[0,.69444,.00316,0,.5]},"SansSerif-Regular":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.31945],34:[0,.69444,0,0,.5],35:[.19444,.69444,0,0,.83334],36:[.05556,.75,0,0,.5],37:[.05556,.75,0,0,.83334],38:[0,.69444,0,0,.75834],39:[0,.69444,0,0,.27778],40:[.25,.75,0,0,.38889],41:[.25,.75,0,0,.38889],42:[0,.75,0,0,.5],43:[.08333,.58333,0,0,.77778],44:[.125,.08333,0,0,.27778],45:[0,.44444,0,0,.33333],46:[0,.08333,0,0,.27778],47:[.25,.75,0,0,.5],48:[0,.65556,0,0,.5],49:[0,.65556,0,0,.5],50:[0,.65556,0,0,.5],51:[0,.65556,0,0,.5],52:[0,.65556,0,0,.5],53:[0,.65556,0,0,.5],54:[0,.65556,0,0,.5],55:[0,.65556,0,0,.5],56:[0,.65556,0,0,.5],57:[0,.65556,0,0,.5],58:[0,.44444,0,0,.27778],59:[.125,.44444,0,0,.27778],61:[-.13,.37,0,0,.77778],63:[0,.69444,0,0,.47222],64:[0,.69444,0,0,.66667],65:[0,.69444,0,0,.66667],66:[0,.69444,0,0,.66667],67:[0,.69444,0,0,.63889],68:[0,.69444,0,0,.72223],69:[0,.69444,0,0,.59722],70:[0,.69444,0,0,.56945],71:[0,.69444,0,0,.66667],72:[0,.69444,0,0,.70834],73:[0,.69444,0,0,.27778],74:[0,.69444,0,0,.47222],75:[0,.69444,0,0,.69445],76:[0,.69444,0,0,.54167],77:[0,.69444,0,0,.875],78:[0,.69444,0,0,.70834],79:[0,.69444,0,0,.73611],80:[0,.69444,0,0,.63889],81:[.125,.69444,0,0,.73611],82:[0,.69444,0,0,.64584],83:[0,.69444,0,0,.55556],84:[0,.69444,0,0,.68056],85:[0,.69444,0,0,.6875],86:[0,.69444,.01389,0,.66667],87:[0,.69444,.01389,0,.94445],88:[0,.69444,0,0,.66667],89:[0,.69444,.025,0,.66667],90:[0,.69444,0,0,.61111],91:[.25,.75,0,0,.28889],93:[.25,.75,0,0,.28889],94:[0,.69444,0,0,.5],95:[.35,.09444,.02778,0,.5],97:[0,.44444,0,0,.48056],98:[0,.69444,0,0,.51667],99:[0,.44444,0,0,.44445],100:[0,.69444,0,0,.51667],101:[0,.44444,0,0,.44445],102:[0,.69444,.06944,0,.30556],103:[.19444,.44444,.01389,0,.5],104:[0,.69444,0,0,.51667],105:[0,.67937,0,0,.23889],106:[.19444,.67937,0,0,.26667],107:[0,.69444,0,0,.48889],108:[0,.69444,0,0,.23889],109:[0,.44444,0,0,.79445],110:[0,.44444,0,0,.51667],111:[0,.44444,0,0,.5],112:[.19444,.44444,0,0,.51667],113:[.19444,.44444,0,0,.51667],114:[0,.44444,.01389,0,.34167],115:[0,.44444,0,0,.38333],116:[0,.57143,0,0,.36111],117:[0,.44444,0,0,.51667],118:[0,.44444,.01389,0,.46111],119:[0,.44444,.01389,0,.68334],120:[0,.44444,0,0,.46111],121:[.19444,.44444,.01389,0,.46111],122:[0,.44444,0,0,.43472],126:[.35,.32659,0,0,.5],160:[0,0,0,0,.25],168:[0,.67937,0,0,.5],176:[0,.69444,0,0,.66667],184:[.17014,0,0,0,.44445],305:[0,.44444,0,0,.23889],567:[.19444,.44444,0,0,.26667],710:[0,.69444,0,0,.5],711:[0,.63194,0,0,.5],713:[0,.60889,0,0,.5],714:[0,.69444,0,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,0,0,.5],729:[0,.67937,0,0,.27778],730:[0,.69444,0,0,.66667],732:[0,.67659,0,0,.5],733:[0,.69444,0,0,.5],915:[0,.69444,0,0,.54167],916:[0,.69444,0,0,.83334],920:[0,.69444,0,0,.77778],923:[0,.69444,0,0,.61111],926:[0,.69444,0,0,.66667],928:[0,.69444,0,0,.70834],931:[0,.69444,0,0,.72222],933:[0,.69444,0,0,.77778],934:[0,.69444,0,0,.72222],936:[0,.69444,0,0,.77778],937:[0,.69444,0,0,.72222],8211:[0,.44444,.02778,0,.5],8212:[0,.44444,.02778,0,1],8216:[0,.69444,0,0,.27778],8217:[0,.69444,0,0,.27778],8220:[0,.69444,0,0,.5],8221:[0,.69444,0,0,.5]},"Script-Regular":{32:[0,0,0,0,.25],65:[0,.7,.22925,0,.80253],66:[0,.7,.04087,0,.90757],67:[0,.7,.1689,0,.66619],68:[0,.7,.09371,0,.77443],69:[0,.7,.18583,0,.56162],70:[0,.7,.13634,0,.89544],71:[0,.7,.17322,0,.60961],72:[0,.7,.29694,0,.96919],73:[0,.7,.19189,0,.80907],74:[.27778,.7,.19189,0,1.05159],75:[0,.7,.31259,0,.91364],76:[0,.7,.19189,0,.87373],77:[0,.7,.15981,0,1.08031],78:[0,.7,.3525,0,.9015],79:[0,.7,.08078,0,.73787],80:[0,.7,.08078,0,1.01262],81:[0,.7,.03305,0,.88282],82:[0,.7,.06259,0,.85],83:[0,.7,.19189,0,.86767],84:[0,.7,.29087,0,.74697],85:[0,.7,.25815,0,.79996],86:[0,.7,.27523,0,.62204],87:[0,.7,.27523,0,.80532],88:[0,.7,.26006,0,.94445],89:[0,.7,.2939,0,.70961],90:[0,.7,.24037,0,.8212],160:[0,0,0,0,.25]},"Size1-Regular":{32:[0,0,0,0,.25],40:[.35001,.85,0,0,.45834],41:[.35001,.85,0,0,.45834],47:[.35001,.85,0,0,.57778],91:[.35001,.85,0,0,.41667],92:[.35001,.85,0,0,.57778],93:[.35001,.85,0,0,.41667],123:[.35001,.85,0,0,.58334],125:[.35001,.85,0,0,.58334],160:[0,0,0,0,.25],710:[0,.72222,0,0,.55556],732:[0,.72222,0,0,.55556],770:[0,.72222,0,0,.55556],771:[0,.72222,0,0,.55556],8214:[-99e-5,.601,0,0,.77778],8593:[1e-5,.6,0,0,.66667],8595:[1e-5,.6,0,0,.66667],8657:[1e-5,.6,0,0,.77778],8659:[1e-5,.6,0,0,.77778],8719:[.25001,.75,0,0,.94445],8720:[.25001,.75,0,0,.94445],8721:[.25001,.75,0,0,1.05556],8730:[.35001,.85,0,0,1],8739:[-.00599,.606,0,0,.33333],8741:[-.00599,.606,0,0,.55556],8747:[.30612,.805,.19445,0,.47222],8748:[.306,.805,.19445,0,.47222],8749:[.306,.805,.19445,0,.47222],8750:[.30612,.805,.19445,0,.47222],8896:[.25001,.75,0,0,.83334],8897:[.25001,.75,0,0,.83334],8898:[.25001,.75,0,0,.83334],8899:[.25001,.75,0,0,.83334],8968:[.35001,.85,0,0,.47222],8969:[.35001,.85,0,0,.47222],8970:[.35001,.85,0,0,.47222],8971:[.35001,.85,0,0,.47222],9168:[-99e-5,.601,0,0,.66667],10216:[.35001,.85,0,0,.47222],10217:[.35001,.85,0,0,.47222],10752:[.25001,.75,0,0,1.11111],10753:[.25001,.75,0,0,1.11111],10754:[.25001,.75,0,0,1.11111],10756:[.25001,.75,0,0,.83334],10758:[.25001,.75,0,0,.83334]},"Size2-Regular":{32:[0,0,0,0,.25],40:[.65002,1.15,0,0,.59722],41:[.65002,1.15,0,0,.59722],47:[.65002,1.15,0,0,.81111],91:[.65002,1.15,0,0,.47222],92:[.65002,1.15,0,0,.81111],93:[.65002,1.15,0,0,.47222],123:[.65002,1.15,0,0,.66667],125:[.65002,1.15,0,0,.66667],160:[0,0,0,0,.25],710:[0,.75,0,0,1],732:[0,.75,0,0,1],770:[0,.75,0,0,1],771:[0,.75,0,0,1],8719:[.55001,1.05,0,0,1.27778],8720:[.55001,1.05,0,0,1.27778],8721:[.55001,1.05,0,0,1.44445],8730:[.65002,1.15,0,0,1],8747:[.86225,1.36,.44445,0,.55556],8748:[.862,1.36,.44445,0,.55556],8749:[.862,1.36,.44445,0,.55556],8750:[.86225,1.36,.44445,0,.55556],8896:[.55001,1.05,0,0,1.11111],8897:[.55001,1.05,0,0,1.11111],8898:[.55001,1.05,0,0,1.11111],8899:[.55001,1.05,0,0,1.11111],8968:[.65002,1.15,0,0,.52778],8969:[.65002,1.15,0,0,.52778],8970:[.65002,1.15,0,0,.52778],8971:[.65002,1.15,0,0,.52778],10216:[.65002,1.15,0,0,.61111],10217:[.65002,1.15,0,0,.61111],10752:[.55001,1.05,0,0,1.51112],10753:[.55001,1.05,0,0,1.51112],10754:[.55001,1.05,0,0,1.51112],10756:[.55001,1.05,0,0,1.11111],10758:[.55001,1.05,0,0,1.11111]},"Size3-Regular":{32:[0,0,0,0,.25],40:[.95003,1.45,0,0,.73611],41:[.95003,1.45,0,0,.73611],47:[.95003,1.45,0,0,1.04445],91:[.95003,1.45,0,0,.52778],92:[.95003,1.45,0,0,1.04445],93:[.95003,1.45,0,0,.52778],123:[.95003,1.45,0,0,.75],125:[.95003,1.45,0,0,.75],160:[0,0,0,0,.25],710:[0,.75,0,0,1.44445],732:[0,.75,0,0,1.44445],770:[0,.75,0,0,1.44445],771:[0,.75,0,0,1.44445],8730:[.95003,1.45,0,0,1],8968:[.95003,1.45,0,0,.58334],8969:[.95003,1.45,0,0,.58334],8970:[.95003,1.45,0,0,.58334],8971:[.95003,1.45,0,0,.58334],10216:[.95003,1.45,0,0,.75],10217:[.95003,1.45,0,0,.75]},"Size4-Regular":{32:[0,0,0,0,.25],40:[1.25003,1.75,0,0,.79167],41:[1.25003,1.75,0,0,.79167],47:[1.25003,1.75,0,0,1.27778],91:[1.25003,1.75,0,0,.58334],92:[1.25003,1.75,0,0,1.27778],93:[1.25003,1.75,0,0,.58334],123:[1.25003,1.75,0,0,.80556],125:[1.25003,1.75,0,0,.80556],160:[0,0,0,0,.25],710:[0,.825,0,0,1.8889],732:[0,.825,0,0,1.8889],770:[0,.825,0,0,1.8889],771:[0,.825,0,0,1.8889],8730:[1.25003,1.75,0,0,1],8968:[1.25003,1.75,0,0,.63889],8969:[1.25003,1.75,0,0,.63889],8970:[1.25003,1.75,0,0,.63889],8971:[1.25003,1.75,0,0,.63889],9115:[.64502,1.155,0,0,.875],9116:[1e-5,.6,0,0,.875],9117:[.64502,1.155,0,0,.875],9118:[.64502,1.155,0,0,.875],9119:[1e-5,.6,0,0,.875],9120:[.64502,1.155,0,0,.875],9121:[.64502,1.155,0,0,.66667],9122:[-99e-5,.601,0,0,.66667],9123:[.64502,1.155,0,0,.66667],9124:[.64502,1.155,0,0,.66667],9125:[-99e-5,.601,0,0,.66667],9126:[.64502,1.155,0,0,.66667],9127:[1e-5,.9,0,0,.88889],9128:[.65002,1.15,0,0,.88889],9129:[.90001,0,0,0,.88889],9130:[0,.3,0,0,.88889],9131:[1e-5,.9,0,0,.88889],9132:[.65002,1.15,0,0,.88889],9133:[.90001,0,0,0,.88889],9143:[.88502,.915,0,0,1.05556],10216:[1.25003,1.75,0,0,.80556],10217:[1.25003,1.75,0,0,.80556],57344:[-.00499,.605,0,0,1.05556],57345:[-.00499,.605,0,0,1.05556],57680:[0,.12,0,0,.45],57681:[0,.12,0,0,.45],57682:[0,.12,0,0,.45],57683:[0,.12,0,0,.45]},"Typewriter-Regular":{32:[0,0,0,0,.525],33:[0,.61111,0,0,.525],34:[0,.61111,0,0,.525],35:[0,.61111,0,0,.525],36:[.08333,.69444,0,0,.525],37:[.08333,.69444,0,0,.525],38:[0,.61111,0,0,.525],39:[0,.61111,0,0,.525],40:[.08333,.69444,0,0,.525],41:[.08333,.69444,0,0,.525],42:[0,.52083,0,0,.525],43:[-.08056,.53055,0,0,.525],44:[.13889,.125,0,0,.525],45:[-.08056,.53055,0,0,.525],46:[0,.125,0,0,.525],47:[.08333,.69444,0,0,.525],48:[0,.61111,0,0,.525],49:[0,.61111,0,0,.525],50:[0,.61111,0,0,.525],51:[0,.61111,0,0,.525],52:[0,.61111,0,0,.525],53:[0,.61111,0,0,.525],54:[0,.61111,0,0,.525],55:[0,.61111,0,0,.525],56:[0,.61111,0,0,.525],57:[0,.61111,0,0,.525],58:[0,.43056,0,0,.525],59:[.13889,.43056,0,0,.525],60:[-.05556,.55556,0,0,.525],61:[-.19549,.41562,0,0,.525],62:[-.05556,.55556,0,0,.525],63:[0,.61111,0,0,.525],64:[0,.61111,0,0,.525],65:[0,.61111,0,0,.525],66:[0,.61111,0,0,.525],67:[0,.61111,0,0,.525],68:[0,.61111,0,0,.525],69:[0,.61111,0,0,.525],70:[0,.61111,0,0,.525],71:[0,.61111,0,0,.525],72:[0,.61111,0,0,.525],73:[0,.61111,0,0,.525],74:[0,.61111,0,0,.525],75:[0,.61111,0,0,.525],76:[0,.61111,0,0,.525],77:[0,.61111,0,0,.525],78:[0,.61111,0,0,.525],79:[0,.61111,0,0,.525],80:[0,.61111,0,0,.525],81:[.13889,.61111,0,0,.525],82:[0,.61111,0,0,.525],83:[0,.61111,0,0,.525],84:[0,.61111,0,0,.525],85:[0,.61111,0,0,.525],86:[0,.61111,0,0,.525],87:[0,.61111,0,0,.525],88:[0,.61111,0,0,.525],89:[0,.61111,0,0,.525],90:[0,.61111,0,0,.525],91:[.08333,.69444,0,0,.525],92:[.08333,.69444,0,0,.525],93:[.08333,.69444,0,0,.525],94:[0,.61111,0,0,.525],95:[.09514,0,0,0,.525],96:[0,.61111,0,0,.525],97:[0,.43056,0,0,.525],98:[0,.61111,0,0,.525],99:[0,.43056,0,0,.525],100:[0,.61111,0,0,.525],101:[0,.43056,0,0,.525],102:[0,.61111,0,0,.525],103:[.22222,.43056,0,0,.525],104:[0,.61111,0,0,.525],105:[0,.61111,0,0,.525],106:[.22222,.61111,0,0,.525],107:[0,.61111,0,0,.525],108:[0,.61111,0,0,.525],109:[0,.43056,0,0,.525],110:[0,.43056,0,0,.525],111:[0,.43056,0,0,.525],112:[.22222,.43056,0,0,.525],113:[.22222,.43056,0,0,.525],114:[0,.43056,0,0,.525],115:[0,.43056,0,0,.525],116:[0,.55358,0,0,.525],117:[0,.43056,0,0,.525],118:[0,.43056,0,0,.525],119:[0,.43056,0,0,.525],120:[0,.43056,0,0,.525],121:[.22222,.43056,0,0,.525],122:[0,.43056,0,0,.525],123:[.08333,.69444,0,0,.525],124:[.08333,.69444,0,0,.525],125:[.08333,.69444,0,0,.525],126:[0,.61111,0,0,.525],127:[0,.61111,0,0,.525],160:[0,0,0,0,.525],176:[0,.61111,0,0,.525],184:[.19445,0,0,0,.525],305:[0,.43056,0,0,.525],567:[.22222,.43056,0,0,.525],711:[0,.56597,0,0,.525],713:[0,.56555,0,0,.525],714:[0,.61111,0,0,.525],715:[0,.61111,0,0,.525],728:[0,.61111,0,0,.525],730:[0,.61111,0,0,.525],770:[0,.61111,0,0,.525],771:[0,.61111,0,0,.525],776:[0,.61111,0,0,.525],915:[0,.61111,0,0,.525],916:[0,.61111,0,0,.525],920:[0,.61111,0,0,.525],923:[0,.61111,0,0,.525],926:[0,.61111,0,0,.525],928:[0,.61111,0,0,.525],931:[0,.61111,0,0,.525],933:[0,.61111,0,0,.525],934:[0,.61111,0,0,.525],936:[0,.61111,0,0,.525],937:[0,.61111,0,0,.525],8216:[0,.61111,0,0,.525],8217:[0,.61111,0,0,.525],8242:[0,.61111,0,0,.525],9251:[.11111,.21944,0,0,.525]}},pf={slant:[.25,.25,.25],space:[0,0,0],stretch:[0,0,0],shrink:[0,0,0],xHeight:[.431,.431,.431],quad:[1,1.171,1.472],extraSpace:[0,0,0],num1:[.677,.732,.925],num2:[.394,.384,.387],num3:[.444,.471,.504],denom1:[.686,.752,1.025],denom2:[.345,.344,.532],sup1:[.413,.503,.504],sup2:[.363,.431,.404],sup3:[.289,.286,.294],sub1:[.15,.143,.2],sub2:[.247,.286,.4],supDrop:[.386,.353,.494],subDrop:[.05,.071,.1],delim1:[2.39,1.7,1.98],delim2:[1.01,1.157,1.42],axisHeight:[.25,.25,.25],defaultRuleThickness:[.04,.049,.049],bigOpSpacing1:[.111,.111,.111],bigOpSpacing2:[.166,.166,.166],bigOpSpacing3:[.2,.2,.2],bigOpSpacing4:[.6,.611,.611],bigOpSpacing5:[.1,.143,.143],sqrtRuleThickness:[.04,.04,.04],ptPerEm:[10,10,10],doubleRuleSep:[.2,.2,.2],arrayRuleWidth:[.04,.04,.04],fboxsep:[.3,.3,.3],fboxrule:[.04,.04,.04]},fS={Å:"A",Ð:"D",Þ:"o",å:"a",ð:"d",þ:"o",А:"A",Б:"B",В:"B",Г:"F",Д:"A",Е:"E",Ж:"K",З:"3",И:"N",Й:"N",К:"K",Л:"N",М:"M",Н:"H",О:"O",П:"N",Р:"P",С:"C",Т:"T",У:"y",Ф:"O",Х:"X",Ц:"U",Ч:"h",Ш:"W",Щ:"W",Ъ:"B",Ы:"X",Ь:"B",Э:"3",Ю:"X",Я:"R",а:"a",б:"b",в:"a",г:"r",д:"y",е:"e",ж:"m",з:"e",и:"n",й:"n",к:"n",л:"n",м:"m",н:"n",о:"o",п:"n",р:"p",с:"c",т:"o",у:"y",ф:"b",х:"x",ц:"n",ч:"n",ш:"w",щ:"w",ъ:"a",ы:"m",ь:"a",э:"e",ю:"m",я:"r"};function oge(n,e){Wi[n]=e}function gb(n,e,t){if(!Wi[e])throw new Error("Font metrics not found for font: "+e+".");var s=n.charCodeAt(0),r=Wi[e][s];if(!r&&n[0]in fS&&(s=fS[n[0]].charCodeAt(0),r=Wi[e][s]),!r&&t==="text"&&gA(s)&&(r=Wi[e][77]),r)return{depth:r[0],height:r[1],italic:r[2],skew:r[3],width:r[4]}}var I1={};function age(n){var e;if(n>=5?e=0:n>=3?e=1:e=2,!I1[e]){var t=I1[e]={cssEmPerMu:pf.quad[e]/18};for(var s in pf)pf.hasOwnProperty(s)&&(t[s]=pf[s][e])}return I1[e]}var lge={bin:1,close:1,inner:1,open:1,punct:1,rel:1},cge={"accent-token":1,mathord:1,"op-token":1,spacing:1,textord:1},Rn={math:{},text:{}};function S(n,e,t,s,r,i){Rn[n][r]={font:e,group:t,replace:s},i&&s&&(Rn[n][s]=Rn[n][r])}var I="math",_e="text",A="main",V="ams",Mn="accent-token",Qe="bin",ar="close",uh="inner",dt="mathord",os="op-token",Fr="open",Ep="punct",H="rel",Lo="spacing",Q="textord";S(I,A,H,"≡","\\equiv",!0);S(I,A,H,"≺","\\prec",!0);S(I,A,H,"≻","\\succ",!0);S(I,A,H,"∼","\\sim",!0);S(I,A,H,"⊥","\\perp");S(I,A,H,"⪯","\\preceq",!0);S(I,A,H,"⪰","\\succeq",!0);S(I,A,H,"≃","\\simeq",!0);S(I,A,H,"∣","\\mid",!0);S(I,A,H,"≪","\\ll",!0);S(I,A,H,"≫","\\gg",!0);S(I,A,H,"≍","\\asymp",!0);S(I,A,H,"∥","\\parallel");S(I,A,H,"⋈","\\bowtie",!0);S(I,A,H,"⌣","\\smile",!0);S(I,A,H,"⊑","\\sqsubseteq",!0);S(I,A,H,"⊒","\\sqsupseteq",!0);S(I,A,H,"≐","\\doteq",!0);S(I,A,H,"⌢","\\frown",!0);S(I,A,H,"∋","\\ni",!0);S(I,A,H,"∝","\\propto",!0);S(I,A,H,"⊢","\\vdash",!0);S(I,A,H,"⊣","\\dashv",!0);S(I,A,H,"∋","\\owns");S(I,A,Ep,".","\\ldotp");S(I,A,Ep,"⋅","\\cdotp");S(I,A,Ep,"⋅","·");S(_e,A,Q,"⋅","·");S(I,A,Q,"#","\\#");S(_e,A,Q,"#","\\#");S(I,A,Q,"&","\\&");S(_e,A,Q,"&","\\&");S(I,A,Q,"ℵ","\\aleph",!0);S(I,A,Q,"∀","\\forall",!0);S(I,A,Q,"ℏ","\\hbar",!0);S(I,A,Q,"∃","\\exists",!0);S(I,A,Q,"∇","\\nabla",!0);S(I,A,Q,"♭","\\flat",!0);S(I,A,Q,"ℓ","\\ell",!0);S(I,A,Q,"♮","\\natural",!0);S(I,A,Q,"♣","\\clubsuit",!0);S(I,A,Q,"℘","\\wp",!0);S(I,A,Q,"♯","\\sharp",!0);S(I,A,Q,"♢","\\diamondsuit",!0);S(I,A,Q,"ℜ","\\Re",!0);S(I,A,Q,"♡","\\heartsuit",!0);S(I,A,Q,"ℑ","\\Im",!0);S(I,A,Q,"♠","\\spadesuit",!0);S(I,A,Q,"§","\\S",!0);S(_e,A,Q,"§","\\S");S(I,A,Q,"¶","\\P",!0);S(_e,A,Q,"¶","\\P");S(I,A,Q,"†","\\dag");S(_e,A,Q,"†","\\dag");S(_e,A,Q,"†","\\textdagger");S(I,A,Q,"‡","\\ddag");S(_e,A,Q,"‡","\\ddag");S(_e,A,Q,"‡","\\textdaggerdbl");S(I,A,ar,"⎱","\\rmoustache",!0);S(I,A,Fr,"⎰","\\lmoustache",!0);S(I,A,ar,"⟯","\\rgroup",!0);S(I,A,Fr,"⟮","\\lgroup",!0);S(I,A,Qe,"∓","\\mp",!0);S(I,A,Qe,"⊖","\\ominus",!0);S(I,A,Qe,"⊎","\\uplus",!0);S(I,A,Qe,"⊓","\\sqcap",!0);S(I,A,Qe,"∗","\\ast");S(I,A,Qe,"⊔","\\sqcup",!0);S(I,A,Qe,"◯","\\bigcirc",!0);S(I,A,Qe,"∙","\\bullet",!0);S(I,A,Qe,"‡","\\ddagger");S(I,A,Qe,"≀","\\wr",!0);S(I,A,Qe,"⨿","\\amalg");S(I,A,Qe,"&","\\And");S(I,A,H,"⟵","\\longleftarrow",!0);S(I,A,H,"⇐","\\Leftarrow",!0);S(I,A,H,"⟸","\\Longleftarrow",!0);S(I,A,H,"⟶","\\longrightarrow",!0);S(I,A,H,"⇒","\\Rightarrow",!0);S(I,A,H,"⟹","\\Longrightarrow",!0);S(I,A,H,"↔","\\leftrightarrow",!0);S(I,A,H,"⟷","\\longleftrightarrow",!0);S(I,A,H,"⇔","\\Leftrightarrow",!0);S(I,A,H,"⟺","\\Longleftrightarrow",!0);S(I,A,H,"↦","\\mapsto",!0);S(I,A,H,"⟼","\\longmapsto",!0);S(I,A,H,"↗","\\nearrow",!0);S(I,A,H,"↩","\\hookleftarrow",!0);S(I,A,H,"↪","\\hookrightarrow",!0);S(I,A,H,"↘","\\searrow",!0);S(I,A,H,"↼","\\leftharpoonup",!0);S(I,A,H,"⇀","\\rightharpoonup",!0);S(I,A,H,"↙","\\swarrow",!0);S(I,A,H,"↽","\\leftharpoondown",!0);S(I,A,H,"⇁","\\rightharpoondown",!0);S(I,A,H,"↖","\\nwarrow",!0);S(I,A,H,"⇌","\\rightleftharpoons",!0);S(I,V,H,"≮","\\nless",!0);S(I,V,H,"","\\@nleqslant");S(I,V,H,"","\\@nleqq");S(I,V,H,"⪇","\\lneq",!0);S(I,V,H,"≨","\\lneqq",!0);S(I,V,H,"","\\@lvertneqq");S(I,V,H,"⋦","\\lnsim",!0);S(I,V,H,"⪉","\\lnapprox",!0);S(I,V,H,"⊀","\\nprec",!0);S(I,V,H,"⋠","\\npreceq",!0);S(I,V,H,"⋨","\\precnsim",!0);S(I,V,H,"⪹","\\precnapprox",!0);S(I,V,H,"≁","\\nsim",!0);S(I,V,H,"","\\@nshortmid");S(I,V,H,"∤","\\nmid",!0);S(I,V,H,"⊬","\\nvdash",!0);S(I,V,H,"⊭","\\nvDash",!0);S(I,V,H,"⋪","\\ntriangleleft");S(I,V,H,"⋬","\\ntrianglelefteq",!0);S(I,V,H,"⊊","\\subsetneq",!0);S(I,V,H,"","\\@varsubsetneq");S(I,V,H,"⫋","\\subsetneqq",!0);S(I,V,H,"","\\@varsubsetneqq");S(I,V,H,"≯","\\ngtr",!0);S(I,V,H,"","\\@ngeqslant");S(I,V,H,"","\\@ngeqq");S(I,V,H,"⪈","\\gneq",!0);S(I,V,H,"≩","\\gneqq",!0);S(I,V,H,"","\\@gvertneqq");S(I,V,H,"⋧","\\gnsim",!0);S(I,V,H,"⪊","\\gnapprox",!0);S(I,V,H,"⊁","\\nsucc",!0);S(I,V,H,"⋡","\\nsucceq",!0);S(I,V,H,"⋩","\\succnsim",!0);S(I,V,H,"⪺","\\succnapprox",!0);S(I,V,H,"≆","\\ncong",!0);S(I,V,H,"","\\@nshortparallel");S(I,V,H,"∦","\\nparallel",!0);S(I,V,H,"⊯","\\nVDash",!0);S(I,V,H,"⋫","\\ntriangleright");S(I,V,H,"⋭","\\ntrianglerighteq",!0);S(I,V,H,"","\\@nsupseteqq");S(I,V,H,"⊋","\\supsetneq",!0);S(I,V,H,"","\\@varsupsetneq");S(I,V,H,"⫌","\\supsetneqq",!0);S(I,V,H,"","\\@varsupsetneqq");S(I,V,H,"⊮","\\nVdash",!0);S(I,V,H,"⪵","\\precneqq",!0);S(I,V,H,"⪶","\\succneqq",!0);S(I,V,H,"","\\@nsubseteqq");S(I,V,Qe,"⊴","\\unlhd");S(I,V,Qe,"⊵","\\unrhd");S(I,V,H,"↚","\\nleftarrow",!0);S(I,V,H,"↛","\\nrightarrow",!0);S(I,V,H,"⇍","\\nLeftarrow",!0);S(I,V,H,"⇏","\\nRightarrow",!0);S(I,V,H,"↮","\\nleftrightarrow",!0);S(I,V,H,"⇎","\\nLeftrightarrow",!0);S(I,V,H,"△","\\vartriangle");S(I,V,Q,"ℏ","\\hslash");S(I,V,Q,"▽","\\triangledown");S(I,V,Q,"◊","\\lozenge");S(I,V,Q,"Ⓢ","\\circledS");S(I,V,Q,"®","\\circledR");S(_e,V,Q,"®","\\circledR");S(I,V,Q,"∡","\\measuredangle",!0);S(I,V,Q,"∄","\\nexists");S(I,V,Q,"℧","\\mho");S(I,V,Q,"Ⅎ","\\Finv",!0);S(I,V,Q,"⅁","\\Game",!0);S(I,V,Q,"‵","\\backprime");S(I,V,Q,"▲","\\blacktriangle");S(I,V,Q,"▼","\\blacktriangledown");S(I,V,Q,"■","\\blacksquare");S(I,V,Q,"⧫","\\blacklozenge");S(I,V,Q,"★","\\bigstar");S(I,V,Q,"∢","\\sphericalangle",!0);S(I,V,Q,"∁","\\complement",!0);S(I,V,Q,"ð","\\eth",!0);S(_e,A,Q,"ð","ð");S(I,V,Q,"╱","\\diagup");S(I,V,Q,"╲","\\diagdown");S(I,V,Q,"□","\\square");S(I,V,Q,"□","\\Box");S(I,V,Q,"◊","\\Diamond");S(I,V,Q,"¥","\\yen",!0);S(_e,V,Q,"¥","\\yen",!0);S(I,V,Q,"✓","\\checkmark",!0);S(_e,V,Q,"✓","\\checkmark");S(I,V,Q,"ℶ","\\beth",!0);S(I,V,Q,"ℸ","\\daleth",!0);S(I,V,Q,"ℷ","\\gimel",!0);S(I,V,Q,"ϝ","\\digamma",!0);S(I,V,Q,"ϰ","\\varkappa");S(I,V,Fr,"┌","\\@ulcorner",!0);S(I,V,ar,"┐","\\@urcorner",!0);S(I,V,Fr,"└","\\@llcorner",!0);S(I,V,ar,"┘","\\@lrcorner",!0);S(I,V,H,"≦","\\leqq",!0);S(I,V,H,"⩽","\\leqslant",!0);S(I,V,H,"⪕","\\eqslantless",!0);S(I,V,H,"≲","\\lesssim",!0);S(I,V,H,"⪅","\\lessapprox",!0);S(I,V,H,"≊","\\approxeq",!0);S(I,V,Qe,"⋖","\\lessdot");S(I,V,H,"⋘","\\lll",!0);S(I,V,H,"≶","\\lessgtr",!0);S(I,V,H,"⋚","\\lesseqgtr",!0);S(I,V,H,"⪋","\\lesseqqgtr",!0);S(I,V,H,"≑","\\doteqdot");S(I,V,H,"≓","\\risingdotseq",!0);S(I,V,H,"≒","\\fallingdotseq",!0);S(I,V,H,"∽","\\backsim",!0);S(I,V,H,"⋍","\\backsimeq",!0);S(I,V,H,"⫅","\\subseteqq",!0);S(I,V,H,"⋐","\\Subset",!0);S(I,V,H,"⊏","\\sqsubset",!0);S(I,V,H,"≼","\\preccurlyeq",!0);S(I,V,H,"⋞","\\curlyeqprec",!0);S(I,V,H,"≾","\\precsim",!0);S(I,V,H,"⪷","\\precapprox",!0);S(I,V,H,"⊲","\\vartriangleleft");S(I,V,H,"⊴","\\trianglelefteq");S(I,V,H,"⊨","\\vDash",!0);S(I,V,H,"⊪","\\Vvdash",!0);S(I,V,H,"⌣","\\smallsmile");S(I,V,H,"⌢","\\smallfrown");S(I,V,H,"≏","\\bumpeq",!0);S(I,V,H,"≎","\\Bumpeq",!0);S(I,V,H,"≧","\\geqq",!0);S(I,V,H,"⩾","\\geqslant",!0);S(I,V,H,"⪖","\\eqslantgtr",!0);S(I,V,H,"≳","\\gtrsim",!0);S(I,V,H,"⪆","\\gtrapprox",!0);S(I,V,Qe,"⋗","\\gtrdot");S(I,V,H,"⋙","\\ggg",!0);S(I,V,H,"≷","\\gtrless",!0);S(I,V,H,"⋛","\\gtreqless",!0);S(I,V,H,"⪌","\\gtreqqless",!0);S(I,V,H,"≖","\\eqcirc",!0);S(I,V,H,"≗","\\circeq",!0);S(I,V,H,"≜","\\triangleq",!0);S(I,V,H,"∼","\\thicksim");S(I,V,H,"≈","\\thickapprox");S(I,V,H,"⫆","\\supseteqq",!0);S(I,V,H,"⋑","\\Supset",!0);S(I,V,H,"⊐","\\sqsupset",!0);S(I,V,H,"≽","\\succcurlyeq",!0);S(I,V,H,"⋟","\\curlyeqsucc",!0);S(I,V,H,"≿","\\succsim",!0);S(I,V,H,"⪸","\\succapprox",!0);S(I,V,H,"⊳","\\vartriangleright");S(I,V,H,"⊵","\\trianglerighteq");S(I,V,H,"⊩","\\Vdash",!0);S(I,V,H,"∣","\\shortmid");S(I,V,H,"∥","\\shortparallel");S(I,V,H,"≬","\\between",!0);S(I,V,H,"⋔","\\pitchfork",!0);S(I,V,H,"∝","\\varpropto");S(I,V,H,"◀","\\blacktriangleleft");S(I,V,H,"∴","\\therefore",!0);S(I,V,H,"∍","\\backepsilon");S(I,V,H,"▶","\\blacktriangleright");S(I,V,H,"∵","\\because",!0);S(I,V,H,"⋘","\\llless");S(I,V,H,"⋙","\\gggtr");S(I,V,Qe,"⊲","\\lhd");S(I,V,Qe,"⊳","\\rhd");S(I,V,H,"≂","\\eqsim",!0);S(I,A,H,"⋈","\\Join");S(I,V,H,"≑","\\Doteq",!0);S(I,V,Qe,"∔","\\dotplus",!0);S(I,V,Qe,"∖","\\smallsetminus");S(I,V,Qe,"⋒","\\Cap",!0);S(I,V,Qe,"⋓","\\Cup",!0);S(I,V,Qe,"⩞","\\doublebarwedge",!0);S(I,V,Qe,"⊟","\\boxminus",!0);S(I,V,Qe,"⊞","\\boxplus",!0);S(I,V,Qe,"⋇","\\divideontimes",!0);S(I,V,Qe,"⋉","\\ltimes",!0);S(I,V,Qe,"⋊","\\rtimes",!0);S(I,V,Qe,"⋋","\\leftthreetimes",!0);S(I,V,Qe,"⋌","\\rightthreetimes",!0);S(I,V,Qe,"⋏","\\curlywedge",!0);S(I,V,Qe,"⋎","\\curlyvee",!0);S(I,V,Qe,"⊝","\\circleddash",!0);S(I,V,Qe,"⊛","\\circledast",!0);S(I,V,Qe,"⋅","\\centerdot");S(I,V,Qe,"⊺","\\intercal",!0);S(I,V,Qe,"⋒","\\doublecap");S(I,V,Qe,"⋓","\\doublecup");S(I,V,Qe,"⊠","\\boxtimes",!0);S(I,V,H,"⇢","\\dashrightarrow",!0);S(I,V,H,"⇠","\\dashleftarrow",!0);S(I,V,H,"⇇","\\leftleftarrows",!0);S(I,V,H,"⇆","\\leftrightarrows",!0);S(I,V,H,"⇚","\\Lleftarrow",!0);S(I,V,H,"↞","\\twoheadleftarrow",!0);S(I,V,H,"↢","\\leftarrowtail",!0);S(I,V,H,"↫","\\looparrowleft",!0);S(I,V,H,"⇋","\\leftrightharpoons",!0);S(I,V,H,"↶","\\curvearrowleft",!0);S(I,V,H,"↺","\\circlearrowleft",!0);S(I,V,H,"↰","\\Lsh",!0);S(I,V,H,"⇈","\\upuparrows",!0);S(I,V,H,"↿","\\upharpoonleft",!0);S(I,V,H,"⇃","\\downharpoonleft",!0);S(I,A,H,"⊶","\\origof",!0);S(I,A,H,"⊷","\\imageof",!0);S(I,V,H,"⊸","\\multimap",!0);S(I,V,H,"↭","\\leftrightsquigarrow",!0);S(I,V,H,"⇉","\\rightrightarrows",!0);S(I,V,H,"⇄","\\rightleftarrows",!0);S(I,V,H,"↠","\\twoheadrightarrow",!0);S(I,V,H,"↣","\\rightarrowtail",!0);S(I,V,H,"↬","\\looparrowright",!0);S(I,V,H,"↷","\\curvearrowright",!0);S(I,V,H,"↻","\\circlearrowright",!0);S(I,V,H,"↱","\\Rsh",!0);S(I,V,H,"⇊","\\downdownarrows",!0);S(I,V,H,"↾","\\upharpoonright",!0);S(I,V,H,"⇂","\\downharpoonright",!0);S(I,V,H,"⇝","\\rightsquigarrow",!0);S(I,V,H,"⇝","\\leadsto");S(I,V,H,"⇛","\\Rrightarrow",!0);S(I,V,H,"↾","\\restriction");S(I,A,Q,"‘","`");S(I,A,Q,"$","\\$");S(_e,A,Q,"$","\\$");S(_e,A,Q,"$","\\textdollar");S(I,A,Q,"%","\\%");S(_e,A,Q,"%","\\%");S(I,A,Q,"_","\\_");S(_e,A,Q,"_","\\_");S(_e,A,Q,"_","\\textunderscore");S(I,A,Q,"∠","\\angle",!0);S(I,A,Q,"∞","\\infty",!0);S(I,A,Q,"′","\\prime");S(I,A,Q,"△","\\triangle");S(I,A,Q,"Γ","\\Gamma",!0);S(I,A,Q,"Δ","\\Delta",!0);S(I,A,Q,"Θ","\\Theta",!0);S(I,A,Q,"Λ","\\Lambda",!0);S(I,A,Q,"Ξ","\\Xi",!0);S(I,A,Q,"Π","\\Pi",!0);S(I,A,Q,"Σ","\\Sigma",!0);S(I,A,Q,"Υ","\\Upsilon",!0);S(I,A,Q,"Φ","\\Phi",!0);S(I,A,Q,"Ψ","\\Psi",!0);S(I,A,Q,"Ω","\\Omega",!0);S(I,A,Q,"A","Α");S(I,A,Q,"B","Β");S(I,A,Q,"E","Ε");S(I,A,Q,"Z","Ζ");S(I,A,Q,"H","Η");S(I,A,Q,"I","Ι");S(I,A,Q,"K","Κ");S(I,A,Q,"M","Μ");S(I,A,Q,"N","Ν");S(I,A,Q,"O","Ο");S(I,A,Q,"P","Ρ");S(I,A,Q,"T","Τ");S(I,A,Q,"X","Χ");S(I,A,Q,"¬","\\neg",!0);S(I,A,Q,"¬","\\lnot");S(I,A,Q,"⊤","\\top");S(I,A,Q,"⊥","\\bot");S(I,A,Q,"∅","\\emptyset");S(I,V,Q,"∅","\\varnothing");S(I,A,dt,"α","\\alpha",!0);S(I,A,dt,"β","\\beta",!0);S(I,A,dt,"γ","\\gamma",!0);S(I,A,dt,"δ","\\delta",!0);S(I,A,dt,"ϵ","\\epsilon",!0);S(I,A,dt,"ζ","\\zeta",!0);S(I,A,dt,"η","\\eta",!0);S(I,A,dt,"θ","\\theta",!0);S(I,A,dt,"ι","\\iota",!0);S(I,A,dt,"κ","\\kappa",!0);S(I,A,dt,"λ","\\lambda",!0);S(I,A,dt,"μ","\\mu",!0);S(I,A,dt,"ν","\\nu",!0);S(I,A,dt,"ξ","\\xi",!0);S(I,A,dt,"ο","\\omicron",!0);S(I,A,dt,"π","\\pi",!0);S(I,A,dt,"ρ","\\rho",!0);S(I,A,dt,"σ","\\sigma",!0);S(I,A,dt,"τ","\\tau",!0);S(I,A,dt,"υ","\\upsilon",!0);S(I,A,dt,"ϕ","\\phi",!0);S(I,A,dt,"χ","\\chi",!0);S(I,A,dt,"ψ","\\psi",!0);S(I,A,dt,"ω","\\omega",!0);S(I,A,dt,"ε","\\varepsilon",!0);S(I,A,dt,"ϑ","\\vartheta",!0);S(I,A,dt,"ϖ","\\varpi",!0);S(I,A,dt,"ϱ","\\varrho",!0);S(I,A,dt,"ς","\\varsigma",!0);S(I,A,dt,"φ","\\varphi",!0);S(I,A,Qe,"∗","*",!0);S(I,A,Qe,"+","+");S(I,A,Qe,"−","-",!0);S(I,A,Qe,"⋅","\\cdot",!0);S(I,A,Qe,"∘","\\circ",!0);S(I,A,Qe,"÷","\\div",!0);S(I,A,Qe,"±","\\pm",!0);S(I,A,Qe,"×","\\times",!0);S(I,A,Qe,"∩","\\cap",!0);S(I,A,Qe,"∪","\\cup",!0);S(I,A,Qe,"∖","\\setminus",!0);S(I,A,Qe,"∧","\\land");S(I,A,Qe,"∨","\\lor");S(I,A,Qe,"∧","\\wedge",!0);S(I,A,Qe,"∨","\\vee",!0);S(I,A,Q,"√","\\surd");S(I,A,Fr,"⟨","\\langle",!0);S(I,A,Fr,"∣","\\lvert");S(I,A,Fr,"∥","\\lVert");S(I,A,ar,"?","?");S(I,A,ar,"!","!");S(I,A,ar,"⟩","\\rangle",!0);S(I,A,ar,"∣","\\rvert");S(I,A,ar,"∥","\\rVert");S(I,A,H,"=","=");S(I,A,H,":",":");S(I,A,H,"≈","\\approx",!0);S(I,A,H,"≅","\\cong",!0);S(I,A,H,"≥","\\ge");S(I,A,H,"≥","\\geq",!0);S(I,A,H,"←","\\gets");S(I,A,H,">","\\gt",!0);S(I,A,H,"∈","\\in",!0);S(I,A,H,"","\\@not");S(I,A,H,"⊂","\\subset",!0);S(I,A,H,"⊃","\\supset",!0);S(I,A,H,"⊆","\\subseteq",!0);S(I,A,H,"⊇","\\supseteq",!0);S(I,V,H,"⊈","\\nsubseteq",!0);S(I,V,H,"⊉","\\nsupseteq",!0);S(I,A,H,"⊨","\\models");S(I,A,H,"←","\\leftarrow",!0);S(I,A,H,"≤","\\le");S(I,A,H,"≤","\\leq",!0);S(I,A,H,"<","\\lt",!0);S(I,A,H,"→","\\rightarrow",!0);S(I,A,H,"→","\\to");S(I,V,H,"≱","\\ngeq",!0);S(I,V,H,"≰","\\nleq",!0);S(I,A,Lo," ","\\ ");S(I,A,Lo," ","\\space");S(I,A,Lo," ","\\nobreakspace");S(_e,A,Lo," ","\\ ");S(_e,A,Lo," "," ");S(_e,A,Lo," ","\\space");S(_e,A,Lo," ","\\nobreakspace");S(I,A,Lo,null,"\\nobreak");S(I,A,Lo,null,"\\allowbreak");S(I,A,Ep,",",",");S(I,A,Ep,";",";");S(I,V,Qe,"⊼","\\barwedge",!0);S(I,V,Qe,"⊻","\\veebar",!0);S(I,A,Qe,"⊙","\\odot",!0);S(I,A,Qe,"⊕","\\oplus",!0);S(I,A,Qe,"⊗","\\otimes",!0);S(I,A,Q,"∂","\\partial",!0);S(I,A,Qe,"⊘","\\oslash",!0);S(I,V,Qe,"⊚","\\circledcirc",!0);S(I,V,Qe,"⊡","\\boxdot",!0);S(I,A,Qe,"△","\\bigtriangleup");S(I,A,Qe,"▽","\\bigtriangledown");S(I,A,Qe,"†","\\dagger");S(I,A,Qe,"⋄","\\diamond");S(I,A,Qe,"⋆","\\star");S(I,A,Qe,"◃","\\triangleleft");S(I,A,Qe,"▹","\\triangleright");S(I,A,Fr,"{","\\{");S(_e,A,Q,"{","\\{");S(_e,A,Q,"{","\\textbraceleft");S(I,A,ar,"}","\\}");S(_e,A,Q,"}","\\}");S(_e,A,Q,"}","\\textbraceright");S(I,A,Fr,"{","\\lbrace");S(I,A,ar,"}","\\rbrace");S(I,A,Fr,"[","\\lbrack",!0);S(_e,A,Q,"[","\\lbrack",!0);S(I,A,ar,"]","\\rbrack",!0);S(_e,A,Q,"]","\\rbrack",!0);S(I,A,Fr,"(","\\lparen",!0);S(I,A,ar,")","\\rparen",!0);S(_e,A,Q,"<","\\textless",!0);S(_e,A,Q,">","\\textgreater",!0);S(I,A,Fr,"⌊","\\lfloor",!0);S(I,A,ar,"⌋","\\rfloor",!0);S(I,A,Fr,"⌈","\\lceil",!0);S(I,A,ar,"⌉","\\rceil",!0);S(I,A,Q,"\\","\\backslash");S(I,A,Q,"∣","|");S(I,A,Q,"∣","\\vert");S(_e,A,Q,"|","\\textbar",!0);S(I,A,Q,"∥","\\|");S(I,A,Q,"∥","\\Vert");S(_e,A,Q,"∥","\\textbardbl");S(_e,A,Q,"~","\\textasciitilde");S(_e,A,Q,"\\","\\textbackslash");S(_e,A,Q,"^","\\textasciicircum");S(I,A,H,"↑","\\uparrow",!0);S(I,A,H,"⇑","\\Uparrow",!0);S(I,A,H,"↓","\\downarrow",!0);S(I,A,H,"⇓","\\Downarrow",!0);S(I,A,H,"↕","\\updownarrow",!0);S(I,A,H,"⇕","\\Updownarrow",!0);S(I,A,os,"∐","\\coprod");S(I,A,os,"⋁","\\bigvee");S(I,A,os,"⋀","\\bigwedge");S(I,A,os,"⨄","\\biguplus");S(I,A,os,"⋂","\\bigcap");S(I,A,os,"⋃","\\bigcup");S(I,A,os,"∫","\\int");S(I,A,os,"∫","\\intop");S(I,A,os,"∬","\\iint");S(I,A,os,"∭","\\iiint");S(I,A,os,"∏","\\prod");S(I,A,os,"∑","\\sum");S(I,A,os,"⨂","\\bigotimes");S(I,A,os,"⨁","\\bigoplus");S(I,A,os,"⨀","\\bigodot");S(I,A,os,"∮","\\oint");S(I,A,os,"∯","\\oiint");S(I,A,os,"∰","\\oiiint");S(I,A,os,"⨆","\\bigsqcup");S(I,A,os,"∫","\\smallint");S(_e,A,uh,"…","\\textellipsis");S(I,A,uh,"…","\\mathellipsis");S(_e,A,uh,"…","\\ldots",!0);S(I,A,uh,"…","\\ldots",!0);S(I,A,uh,"⋯","\\@cdots",!0);S(I,A,uh,"⋱","\\ddots",!0);S(I,A,Q,"⋮","\\varvdots");S(_e,A,Q,"⋮","\\varvdots");S(I,A,Mn,"ˊ","\\acute");S(I,A,Mn,"ˋ","\\grave");S(I,A,Mn,"¨","\\ddot");S(I,A,Mn,"~","\\tilde");S(I,A,Mn,"ˉ","\\bar");S(I,A,Mn,"˘","\\breve");S(I,A,Mn,"ˇ","\\check");S(I,A,Mn,"^","\\hat");S(I,A,Mn,"⃗","\\vec");S(I,A,Mn,"˙","\\dot");S(I,A,Mn,"˚","\\mathring");S(I,A,dt,"","\\@imath");S(I,A,dt,"","\\@jmath");S(I,A,Q,"ı","ı");S(I,A,Q,"ȷ","ȷ");S(_e,A,Q,"ı","\\i",!0);S(_e,A,Q,"ȷ","\\j",!0);S(_e,A,Q,"ß","\\ss",!0);S(_e,A,Q,"æ","\\ae",!0);S(_e,A,Q,"œ","\\oe",!0);S(_e,A,Q,"ø","\\o",!0);S(_e,A,Q,"Æ","\\AE",!0);S(_e,A,Q,"Œ","\\OE",!0);S(_e,A,Q,"Ø","\\O",!0);S(_e,A,Mn,"ˊ","\\'");S(_e,A,Mn,"ˋ","\\`");S(_e,A,Mn,"ˆ","\\^");S(_e,A,Mn,"˜","\\~");S(_e,A,Mn,"ˉ","\\=");S(_e,A,Mn,"˘","\\u");S(_e,A,Mn,"˙","\\.");S(_e,A,Mn,"¸","\\c");S(_e,A,Mn,"˚","\\r");S(_e,A,Mn,"ˇ","\\v");S(_e,A,Mn,"¨",'\\"');S(_e,A,Mn,"˝","\\H");S(_e,A,Mn,"◯","\\textcircled");var wA={"--":!0,"---":!0,"``":!0,"''":!0};S(_e,A,Q,"–","--",!0);S(_e,A,Q,"–","\\textendash");S(_e,A,Q,"—","---",!0);S(_e,A,Q,"—","\\textemdash");S(_e,A,Q,"‘","`",!0);S(_e,A,Q,"‘","\\textquoteleft");S(_e,A,Q,"’","'",!0);S(_e,A,Q,"’","\\textquoteright");S(_e,A,Q,"“","``",!0);S(_e,A,Q,"“","\\textquotedblleft");S(_e,A,Q,"”","''",!0);S(_e,A,Q,"”","\\textquotedblright");S(I,A,Q,"°","\\degree",!0);S(_e,A,Q,"°","\\degree");S(_e,A,Q,"°","\\textdegree",!0);S(I,A,Q,"£","\\pounds");S(I,A,Q,"£","\\mathsterling",!0);S(_e,A,Q,"£","\\pounds");S(_e,A,Q,"£","\\textsterling",!0);S(I,V,Q,"✠","\\maltese");S(_e,V,Q,"✠","\\maltese");var mS='0123456789/@."';for(var E1=0;E1{var t=n.charCodeAt(0),s=n.charCodeAt(1),r=(t-55296)*1024+(s-56320)+65536,i=e==="math"?0:1;if(119808<=r&&r<120484){var o=Math.floor((r-119808)/26);return[gf[o][2],gf[o][i]]}else if(120782<=r&&r<=120831){var a=Math.floor((r-120782)/10);return[bS[a][2],bS[a][i]]}else{if(r===120485||r===120486)return[gf[0][2],gf[0][i]];if(1204860)return Ks(i,c,r,t,o.concat(u));if(l){var h,d;if(l==="boldsymbol"){var p=hge(i,r,t,o,s);h=p.fontName,d=[p.fontClass]}else a?(h=qx[l].fontName,d=[l]):(h=xf(l,t.fontWeight,t.fontShape),d=[l,t.fontWeight,t.fontShape]);if(ug(i,h,r).metrics)return Ks(i,h,r,t,o.concat(d));if(wA.hasOwnProperty(i)&&h.slice(0,10)==="Typewriter"){for(var f=[],x=0;x{if(ma(n.classes)!==ma(e.classes)||n.skew!==e.skew||n.maxFontSize!==e.maxFontSize||n.italic!==0&&n.hasClass("mathnormal"))return!1;if(n.classes.length===1){var t=n.classes[0];if(t==="mbin"||t==="mord")return!1}for(var s of Object.keys(n.style))if(n.style[s]!==e.style[s])return!1;for(var r of Object.keys(e.style))if(n.style[r]!==e.style[r])return!1;return!0},SA=n=>{for(var e=0;et&&(t=o.height),o.depth>s&&(s=o.depth),o.maxFontSize>r&&(r=o.maxFontSize)}e.height=t,e.depth=s,e.maxFontSize=r},Ee=function(e,t,s,r){var i=new ch(e,t,s,r);return vb(i),i},xa=(n,e,t,s)=>new ch(n,e,t,s),qc=function(e,t,s){var r=Ee([e],[],t);return r.height=Math.max(s||t.fontMetrics().defaultRuleThickness,t.minRuleThickness),r.style.borderBottomWidth=Ne(r.height),r.maxFontSize=1,r},pge=function(e,t,s,r){var i=new cg(e,t,s,r);return vb(i),i},Fo=function(e){var t=new lh(e);return vb(t),t},Xc=function(e,t){return e instanceof lh?Ee([],[e],t):e},fge=function(e){if(e.positionType==="individualShift"){for(var t=e.children,s=[t[0]],r=-t[0].shift-t[0].elem.depth,i=r,o=1;o{var t=Ee(["mspace"],[],e),s=Dn(n,e);return t.style.marginRight=Ne(s),t},xf=function(e,t,s){var r="";switch(e){case"amsrm":r="AMS";break;case"textrm":r="Main";break;case"textsf":r="SansSerif";break;case"texttt":r="Typewriter";break;default:r=e}var i;return t==="textbf"&&s==="textit"?i="BoldItalic":t==="textbf"?i="Bold":t==="textit"?i="Italic":i="Regular",r+"-"+i},qx={mathbf:{variant:"bold",fontName:"Main-Bold"},mathrm:{variant:"normal",fontName:"Main-Regular"},textit:{variant:"italic",fontName:"Main-Italic"},mathit:{variant:"italic",fontName:"Main-Italic"},mathnormal:{variant:"italic",fontName:"Math-Italic"},mathsfit:{variant:"sans-serif-italic",fontName:"SansSerif-Italic"},mathbb:{variant:"double-struck",fontName:"AMS-Regular"},mathcal:{variant:"script",fontName:"Caligraphic-Regular"},mathfrak:{variant:"fraktur",fontName:"Fraktur-Regular"},mathscr:{variant:"script",fontName:"Script-Regular"},mathsf:{variant:"sans-serif",fontName:"SansSerif-Regular"},mathtt:{variant:"monospace",fontName:"Typewriter-Regular"}},_A={vec:["vec",.471,.714],oiintSize1:["oiintSize1",.957,.499],oiintSize2:["oiintSize2",1.472,.659],oiiintSize1:["oiiintSize1",1.304,.499],oiiintSize2:["oiiintSize2",1.98,.659]},TA=function(e,t){var[s,r,i]=_A[e],o=new ga(s),a=new Mo([o],{width:Ne(r),height:Ne(i),style:"width:"+Ne(r),viewBox:"0 0 "+1e3*r+" "+1e3*i,preserveAspectRatio:"xMinYMin"}),l=xa(["overlay"],[a],t);return l.height=i,l.style.height=Ne(i),l.style.width=Ne(r),l},$n={number:3,unit:"mu"},Ua={number:4,unit:"mu"},mo={number:5,unit:"mu"},mge={mord:{mop:$n,mbin:Ua,mrel:mo,minner:$n},mop:{mord:$n,mop:$n,mrel:mo,minner:$n},mbin:{mord:Ua,mop:Ua,mopen:Ua,minner:Ua},mrel:{mord:mo,mop:mo,mopen:mo,minner:mo},mopen:{},mclose:{mop:$n,mbin:Ua,mrel:mo,minner:$n},mpunct:{mord:$n,mop:$n,mrel:mo,mopen:$n,mclose:$n,mpunct:$n,minner:$n},minner:{mord:$n,mop:$n,mbin:Ua,mrel:mo,mopen:$n,mpunct:$n,minner:$n}},gge={mord:{mop:$n},mop:{mord:$n,mop:$n},mbin:{},mrel:{},mopen:{},mclose:{mop:$n},mpunct:{},minner:{mop:$n}},IA={},g0={},x0={};function Ye(n){for(var{type:e,names:t,props:s,handler:r,htmlBuilder:i,mathmlBuilder:o}=n,a={type:e,numArgs:s.numArgs,argTypes:s.argTypes,allowedInArgument:!!s.allowedInArgument,allowedInText:!!s.allowedInText,allowedInMath:s.allowedInMath===void 0?!0:s.allowedInMath,numOptionalArgs:s.numOptionalArgs||0,infix:!!s.infix,primitive:!!s.primitive,handler:r},l=0;l{var m=x.classes[0],g=f.classes[0];m==="mbin"&&vge.has(g)?x.classes[0]="mord":g==="mbin"&&xge.has(m)&&(f.classes[0]="mord")},{node:h},d,p),Xx(i,(f,x)=>{var m,g,v=jx(x),b=jx(f),y=v&&b?f.hasClass("mtight")?(m=gge[v])==null?void 0:m[b]:(g=mge[v])==null?void 0:g[b]:null;if(y)return CA(y,c)},{node:h},d,p),i},Xx=function(e,t,s,r,i){r&&e.push(r);for(var o=0;od=>{e.splice(h+1,0,d),o++})(o)}r&&e.pop()},EA=function(e){return e instanceof lh||e instanceof cg||e instanceof ch&&e.hasClass("enclosing")?e:null},Kx=function(e,t){var s=EA(e);if(s){var r=s.children;if(r.length){if(t==="right")return Kx(r[r.length-1],"right");if(t==="left")return Kx(r[0],"left")}}return e},jx=function(e,t){if(!e)return null;t&&(e=Kx(e,t));var s=e.classes[0];return yge[s]||null},ed=function(e,t){var s=["nulldelimiter"].concat(e.baseSizingClasses());return Ee(t.concat(s))},tn=function(e,t,s){if(!e)return Ee();if(g0[e.type]){var r=g0[e.type](e,t);if(s&&t.size!==s.size){r=Ee(t.sizingClasses(s),[r],t);var i=t.sizeMultiplier/s.sizeMultiplier;r.height*=i,r.depth*=i}return r}else throw new Ae("Got group of unknown type: '"+e.type+"'")};function vf(n,e){var t=Ee(["base"],n,e),s=Ee(["strut"]);return s.style.height=Ne(t.height+t.depth),t.depth&&(s.style.verticalAlign=Ne(-t.depth)),t.children.unshift(s),t}function Yx(n,e){var t=null;n.length===1&&n[0].type==="tag"&&(t=n[0].tag,n=n[0].body);var s=ms(n,e,"root"),r;s.length===2&&s[1].hasClass("tag")&&(r=s.pop());for(var i=[],o=[],a=0;a0&&(i.push(vf(o,e)),o=[]),i.push(s[a]));o.length>0&&i.push(vf(o,e));var c;t?(c=vf(ms(t,e,!0),e),c.classes=["tag"],i.push(c)):r&&i.push(r);var u=Ee(["katex-html"],i);if(u.setAttribute("aria-hidden","true"),c){var h=c.children[0];h.style.height=Ne(u.height+u.depth),u.depth&&(h.style.verticalAlign=Ne(-u.depth))}return u}function kA(n){return new lh(n)}class Re{constructor(e,t,s){this.type=e,this.attributes={},this.children=t||[],this.classes=s||[]}setAttribute(e,t){this.attributes[e]=t}getAttribute(e){return this.attributes[e]}toNode(){var e=document.createElementNS("http://www.w3.org/1998/Math/MathML",this.type);for(var t in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,t)&&e.setAttribute(t,this.attributes[t]);this.classes.length>0&&(e.className=ma(this.classes));for(var s=0;s0&&(e+=' class ="'+Bs(ma(this.classes))+'"'),e+=">";for(var s=0;s",e}toText(){return this.children.map(e=>e.toText()).join("")}}class ts{constructor(e){this.text=e}toNode(){return document.createTextNode(this.text)}toMarkup(){return Bs(this.toText())}toText(){return this.text}}class AA{constructor(e){this.width=e,e>=.05555&&e<=.05556?this.character=" ":e>=.1666&&e<=.1667?this.character=" ":e>=.2222&&e<=.2223?this.character=" ":e>=.2777&&e<=.2778?this.character="  ":e>=-.05556&&e<=-.05555?this.character=" ⁣":e>=-.1667&&e<=-.1666?this.character=" ⁣":e>=-.2223&&e<=-.2222?this.character=" ⁣":e>=-.2778&&e<=-.2777?this.character=" ⁣":this.character=null}toNode(){if(this.character)return document.createTextNode(this.character);var e=document.createElementNS("http://www.w3.org/1998/Math/MathML","mspace");return e.setAttribute("width",Ne(this.width)),e}toMarkup(){return this.character?""+this.character+"":''}toText(){return this.character?this.character:" "}}var wge=new Set(["\\imath","\\jmath"]),Sge=new Set(["mrow","mtable"]),ni=function(e,t,s){return Rn[t][e]&&Rn[t][e].replace&&e.charCodeAt(0)!==55349&&!(wA.hasOwnProperty(e)&&s&&(s.fontFamily&&s.fontFamily.slice(4,6)==="tt"||s.font&&s.font.slice(4,6)==="tt"))&&(e=Rn[t][e].replace),new ts(e)},bb=function(e){return e.length===1?e[0]:new Re("mrow",e)},yb=function(e,t){if(t.fontFamily==="texttt")return"monospace";if(t.fontFamily==="textsf")return t.fontShape==="textit"&&t.fontWeight==="textbf"?"sans-serif-bold-italic":t.fontShape==="textit"?"sans-serif-italic":t.fontWeight==="textbf"?"bold-sans-serif":"sans-serif";if(t.fontShape==="textit"&&t.fontWeight==="textbf")return"bold-italic";if(t.fontShape==="textit")return"italic";if(t.fontWeight==="textbf")return"bold";var s=t.font;if(!s||s==="mathnormal")return null;var r=e.mode;if(s==="mathit")return"italic";if(s==="boldsymbol")return e.type==="textord"?"bold":"bold-italic";if(s==="mathbf")return"bold";if(s==="mathbb")return"double-struck";if(s==="mathsfit")return"sans-serif-italic";if(s==="mathfrak")return"fraktur";if(s==="mathscr"||s==="mathcal")return"script";if(s==="mathsf")return"sans-serif";if(s==="mathtt")return"monospace";var i=e.text;if(wge.has(i))return null;if(Rn[r][i]){var o=Rn[r][i].replace;o&&(i=o)}var a=qx[s].fontName;return gb(i,a,r)?qx[s].variant:null};function M1(n){if(!n)return!1;if(n.type==="mi"&&n.children.length===1){var e=n.children[0];return e instanceof ts&&e.text==="."}else if(n.type==="mo"&&n.children.length===1&&n.getAttribute("separator")==="true"&&n.getAttribute("lspace")==="0em"&&n.getAttribute("rspace")==="0em"){var t=n.children[0];return t instanceof ts&&t.text===","}else return!1}var Or=function(e,t,s){if(e.length===1){var r=mn(e[0],t);return s&&r instanceof Re&&r.type==="mo"&&(r.setAttribute("lspace","0em"),r.setAttribute("rspace","0em")),[r]}for(var i=[],o,a=0;a=1&&(o.type==="mn"||M1(o))){var c=l.children[0];c instanceof Re&&c.type==="mn"&&(c.children=[...o.children,...c.children],i.pop())}else if(o.type==="mi"&&o.children.length===1){var u=o.children[0];if(u instanceof ts&&u.text==="̸"&&(l.type==="mo"||l.type==="mi"||l.type==="mn")){var h=l.children[0];h instanceof ts&&h.text.length>0&&(h.text=h.text.slice(0,1)+"̸"+h.text.slice(1),i.pop())}}}i.push(l),o=l}return i},va=function(e,t,s){return bb(Or(e,t,s))},mn=function(e,t){if(!e)return new Re("mrow");if(x0[e.type]){var s=x0[e.type](e,t);return s}else throw new Ae("Got group of unknown type: '"+e.type+"'")};function yS(n,e,t,s,r){var i=Or(n,t),o;i.length===1&&i[0]instanceof Re&&Sge.has(i[0].type)?o=i[0]:o=new Re("mrow",i);var a=new Re("annotation",[new ts(e)]);a.setAttribute("encoding","application/x-tex");var l=new Re("semantics",[o,a]),c=new Re("math",[l]);c.setAttribute("xmlns","http://www.w3.org/1998/Math/MathML"),s&&c.setAttribute("display","block");var u=r?"katex":"katex-mathml";return Ee([u],[c])}var Cge=[[1,1,1],[2,1,1],[3,1,1],[4,2,1],[5,2,1],[6,3,1],[7,4,2],[8,6,3],[9,7,6],[10,8,7],[11,10,9]],wS=[.5,.6,.7,.8,.9,1,1.2,1.44,1.728,2.074,2.488],SS=function(e,t){return t.size<2?e:Cge[e-1][t.size-1]};class vo{constructor(e){this.style=e.style,this.color=e.color,this.size=e.size||vo.BASESIZE,this.textSize=e.textSize||this.size,this.phantom=!!e.phantom,this.font=e.font||"",this.fontFamily=e.fontFamily||"",this.fontWeight=e.fontWeight||"",this.fontShape=e.fontShape||"",this.sizeMultiplier=wS[this.size-1],this.maxSize=e.maxSize,this.minRuleThickness=e.minRuleThickness,this._fontMetrics=void 0}extend(e){var t={style:this.style,size:this.size,textSize:this.textSize,color:this.color,phantom:this.phantom,font:this.font,fontFamily:this.fontFamily,fontWeight:this.fontWeight,fontShape:this.fontShape,maxSize:this.maxSize,minRuleThickness:this.minRuleThickness};return Object.assign(t,e),new vo(t)}havingStyle(e){return this.style===e?this:this.extend({style:e,size:SS(this.textSize,e)})}havingCrampedStyle(){return this.havingStyle(this.style.cramp())}havingSize(e){return this.size===e&&this.textSize===e?this:this.extend({style:this.style.text(),size:e,textSize:e,sizeMultiplier:wS[e-1]})}havingBaseStyle(e){e=e||this.style.text();var t=SS(vo.BASESIZE,e);return this.size===t&&this.textSize===vo.BASESIZE&&this.style===e?this:this.extend({style:e,size:t})}havingBaseSizing(){var e;switch(this.style.id){case 4:case 5:e=3;break;case 6:case 7:e=1;break;default:e=6}return this.extend({style:this.style.text(),size:e})}withColor(e){return this.extend({color:e})}withPhantom(){return this.extend({phantom:!0})}withFont(e){return this.extend({font:e})}withTextFontFamily(e){return this.extend({fontFamily:e,font:""})}withTextFontWeight(e){return this.extend({fontWeight:e,font:""})}withTextFontShape(e){return this.extend({fontShape:e,font:""})}sizingClasses(e){return e.size!==this.size?["sizing","reset-size"+e.size,"size"+this.size]:[]}baseSizingClasses(){return this.size!==vo.BASESIZE?["sizing","reset-size"+this.size,"size"+vo.BASESIZE]:[]}fontMetrics(){return this._fontMetrics||(this._fontMetrics=age(this.size)),this._fontMetrics}getColor(){return this.phantom?"transparent":this.color}}vo.BASESIZE=6;var RA=function(e){return new vo({style:e.displayMode?kt.DISPLAY:kt.TEXT,maxSize:e.maxSize,minRuleThickness:e.minRuleThickness})},MA=function(e,t){if(t.displayMode){var s=["katex-display"];t.leqno&&s.push("leqno"),t.fleqn&&s.push("fleqn"),e=Ee(s,[e])}return e},_ge=function(e,t,s){var r=RA(s),i;if(s.output==="mathml")return yS(e,t,r,s.displayMode,!0);if(s.output==="html"){var o=Yx(e,r);i=Ee(["katex"],[o])}else{var a=yS(e,t,r,s.displayMode,!1),l=Yx(e,r);i=Ee(["katex"],[a,l])}return MA(i,s)},Tge=function(e,t,s){var r=RA(s),i=Yx(e,r),o=Ee(["katex"],[i]);return MA(o,s)},Ige={widehat:"^",widecheck:"ˇ",widetilde:"~",utilde:"~",overleftarrow:"←",underleftarrow:"←",xleftarrow:"←",overrightarrow:"→",underrightarrow:"→",xrightarrow:"→",underbrace:"⏟",overbrace:"⏞",underbracket:"⎵",overbracket:"⎴",overgroup:"⏠",undergroup:"⏡",overleftrightarrow:"↔",underleftrightarrow:"↔",xleftrightarrow:"↔",Overrightarrow:"⇒",xRightarrow:"⇒",overleftharpoon:"↼",xleftharpoonup:"↼",overrightharpoon:"⇀",xrightharpoonup:"⇀",xLeftarrow:"⇐",xLeftrightarrow:"⇔",xhookleftarrow:"↩",xhookrightarrow:"↪",xmapsto:"↦",xrightharpoondown:"⇁",xleftharpoondown:"↽",xrightleftharpoons:"⇌",xleftrightharpoons:"⇋",xtwoheadleftarrow:"↞",xtwoheadrightarrow:"↠",xlongequal:"=",xtofrom:"⇄",xrightleftarrows:"⇄",xrightequilibrium:"⇌",xleftequilibrium:"⇋","\\cdrightarrow":"→","\\cdleftarrow":"←","\\cdlongequal":"="},dg=function(e){var t=new Re("mo",[new ts(Ige[e.replace(/^\\/,"")])]);return t.setAttribute("stretchy","true"),t},Ege={overrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],overleftarrow:[["leftarrow"],.888,522,"xMinYMin"],underrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],underleftarrow:[["leftarrow"],.888,522,"xMinYMin"],xrightarrow:[["rightarrow"],1.469,522,"xMaxYMin"],"\\cdrightarrow":[["rightarrow"],3,522,"xMaxYMin"],xleftarrow:[["leftarrow"],1.469,522,"xMinYMin"],"\\cdleftarrow":[["leftarrow"],3,522,"xMinYMin"],Overrightarrow:[["doublerightarrow"],.888,560,"xMaxYMin"],xRightarrow:[["doublerightarrow"],1.526,560,"xMaxYMin"],xLeftarrow:[["doubleleftarrow"],1.526,560,"xMinYMin"],overleftharpoon:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoonup:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoondown:[["leftharpoondown"],.888,522,"xMinYMin"],overrightharpoon:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoonup:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoondown:[["rightharpoondown"],.888,522,"xMaxYMin"],xlongequal:[["longequal"],.888,334,"xMinYMin"],"\\cdlongequal":[["longequal"],3,334,"xMinYMin"],xtwoheadleftarrow:[["twoheadleftarrow"],.888,334,"xMinYMin"],xtwoheadrightarrow:[["twoheadrightarrow"],.888,334,"xMaxYMin"],overleftrightarrow:[["leftarrow","rightarrow"],.888,522],overbrace:[["leftbrace","midbrace","rightbrace"],1.6,548],underbrace:[["leftbraceunder","midbraceunder","rightbraceunder"],1.6,548],underleftrightarrow:[["leftarrow","rightarrow"],.888,522],xleftrightarrow:[["leftarrow","rightarrow"],1.75,522],xLeftrightarrow:[["doubleleftarrow","doublerightarrow"],1.75,560],xrightleftharpoons:[["leftharpoondownplus","rightharpoonplus"],1.75,716],xleftrightharpoons:[["leftharpoonplus","rightharpoondownplus"],1.75,716],xhookleftarrow:[["leftarrow","righthook"],1.08,522],xhookrightarrow:[["lefthook","rightarrow"],1.08,522],overlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],underlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],overbracket:[["leftbracketover","rightbracketover"],1.6,440],underbracket:[["leftbracketunder","rightbracketunder"],1.6,410],overgroup:[["leftgroup","rightgroup"],.888,342],undergroup:[["leftgroupunder","rightgroupunder"],.888,342],xmapsto:[["leftmapsto","rightarrow"],1.5,522],xtofrom:[["leftToFrom","rightToFrom"],1.75,528],xrightleftarrows:[["baraboveleftarrow","rightarrowabovebar"],1.75,901],xrightequilibrium:[["baraboveshortleftharpoon","rightharpoonaboveshortbar"],1.75,716],xleftequilibrium:[["shortbaraboveleftharpoon","shortrightharpoonabovebar"],1.75,716]},kge=new Set(["widehat","widecheck","widetilde","utilde"]),pg=function(e,t){function s(){var a=4e5,l=e.label.slice(1);if(kge.has(l)){var c=e,u=c.base.type==="ordgroup"?c.base.body.length:1,h,d,p;if(u>5)l==="widehat"||l==="widecheck"?(h=420,a=2364,p=.42,d=l+"4"):(h=312,a=2340,p=.34,d="tilde4");else{var f=[1,1,2,2,3,3][u];l==="widehat"||l==="widecheck"?(a=[0,1062,2364,2364,2364][f],h=[0,239,300,360,420][f],p=[0,.24,.3,.3,.36,.42][f],d=l+f):(a=[0,600,1033,2339,2340][f],h=[0,260,286,306,312][f],p=[0,.26,.286,.3,.306,.34][f],d="tilde"+f)}var x=new ga(d),m=new Mo([x],{width:"100%",height:Ne(p),viewBox:"0 0 "+a+" "+h,preserveAspectRatio:"none"});return{span:xa([],[m],t),minWidth:0,height:p}}else{var g=[],v=Ege[l],[b,y,w]=v,C=w/1e3,T=b.length,E,R;if(T===1){var _=v[3];E=["hide-tail"],R=[_]}else if(T===2)E=["halfarrow-left","halfarrow-right"],R=["xMinYMin","xMaxYMin"];else if(T===3)E=["brace-left","brace-center","brace-right"],R=["xMinYMin","xMidYMin","xMaxYMin"];else throw new Error(`Correct katexImagesData or update code here to support + `+T+" children.");for(var k=0;k0&&(r.style.minWidth=Ne(i)),r},Age=function(e,t,s,r,i){var o,a=e.height+e.depth+s+r;if(/fbox|color|angl/.test(t)){if(o=Ee(["stretchy",t],[],i),t==="fbox"){var l=i.color&&i.getColor();l&&(o.style.borderColor=l)}}else{var c=[];/^[bx]cancel$/.test(t)&&c.push(new Gx({x1:"0",y1:"0",x2:"100%",y2:"100%","stroke-width":"0.046em"})),/^x?cancel$/.test(t)&&c.push(new Gx({x1:"0",y1:"100%",x2:"100%",y2:"0","stroke-width":"0.046em"}));var u=new Mo(c,{width:"100%",height:Ne(a)});o=xa([],[u],i)}return o.height=a,o.style.height=Ne(a),o};function Dt(n,e){if(!n||n.type!==e)throw new Error("Expected node of type "+e+", but got "+(n?"node of type "+n.type:String(n)));return n}function fg(n){var e=mg(n);if(!e)throw new Error("Expected node of symbol group type, but got "+(n?"node of type "+n.type:String(n)));return e}function mg(n){return n&&(n.type==="atom"||cge.hasOwnProperty(n.type))?n:null}var NA=n=>{if(n instanceof Nr)return n;if(ige(n)&&n.children.length===1)return NA(n.children[0])},wb=(n,e)=>{var t,s,r;n&&n.type==="supsub"?(s=Dt(n.base,"accent"),t=s.base,n.base=t,r=rge(tn(n,e)),n.base=s):(s=Dt(n,"accent"),t=s.base);var i=tn(t,e.havingCrampedStyle()),o=s.isShifty&&Po(t),a=0;if(o){var l,c;a=(l=(c=NA(i))==null?void 0:c.skew)!=null?l:0}var u=s.label==="\\c",h=u?i.height+i.depth:Math.min(i.height,e.fontMetrics().xHeight),d;if(s.isStretchy)d=pg(s,e),d=Qt({positionType:"firstBaseline",children:[{type:"elem",elem:i},{type:"elem",elem:d,wrapperClasses:["svg-align"],wrapperStyle:a>0?{width:"calc(100% - "+Ne(2*a)+")",marginLeft:Ne(2*a)}:void 0}]});else{var p,f;s.label==="\\vec"?(p=TA("vec",e),f=_A.vec[1]):(p=hg({mode:s.mode,text:s.label},e,"textord"),p=sge(p),p.italic=0,f=p.width,u&&(h+=p.depth)),d=Ee(["accent-body"],[p]);var x=s.label==="\\textcircled";x&&(d.classes.push("accent-full"),h=i.height);var m=a;x||(m-=f/2),d.style.left=Ne(m),s.label==="\\textcircled"&&(d.style.top=".2em"),d=Qt({positionType:"firstBaseline",children:[{type:"elem",elem:i},{type:"kern",size:-h},{type:"elem",elem:d}]})}var g=Ee(["mord","accent"],[d],e);return r?(r.children[0]=g,r.height=Math.max(g.height,r.height),r.classes[0]="mord",r):g},$A=(n,e)=>{var t=n.isStretchy?dg(n.label):new Re("mo",[ni(n.label,n.mode)]),s=new Re("mover",[mn(n.base,e),t]);return s.setAttribute("accent","true"),s},Rge=new RegExp(["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring"].map(n=>"\\"+n).join("|"));Ye({type:"accent",names:["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring","\\widecheck","\\widehat","\\widetilde","\\overrightarrow","\\overleftarrow","\\Overrightarrow","\\overleftrightarrow","\\overgroup","\\overlinesegment","\\overleftharpoon","\\overrightharpoon"],props:{numArgs:1},handler:(n,e)=>{var t=v0(e[0]),s=!Rge.test(n.funcName),r=!s||n.funcName==="\\widehat"||n.funcName==="\\widetilde"||n.funcName==="\\widecheck";return{type:"accent",mode:n.parser.mode,label:n.funcName,isStretchy:s,isShifty:r,base:t}},htmlBuilder:wb,mathmlBuilder:$A});Ye({type:"accent",names:["\\'","\\`","\\^","\\~","\\=","\\u","\\.",'\\"',"\\c","\\r","\\H","\\v","\\textcircled"],props:{numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:["primitive"]},handler:(n,e)=>{var t=e[0],s=n.parser.mode;return s==="math"&&(n.parser.settings.reportNonstrict("mathVsTextAccents","LaTeX's accent "+n.funcName+" works only in text mode"),s="text"),{type:"accent",mode:s,label:n.funcName,isStretchy:!1,isShifty:!0,base:t}},htmlBuilder:wb,mathmlBuilder:$A});Ye({type:"accentUnder",names:["\\underleftarrow","\\underrightarrow","\\underleftrightarrow","\\undergroup","\\underlinesegment","\\utilde"],props:{numArgs:1},handler:(n,e)=>{var{parser:t,funcName:s}=n,r=e[0];return{type:"accentUnder",mode:t.mode,label:s,base:r}},htmlBuilder:(n,e)=>{var t=tn(n.base,e),s=pg(n,e),r=n.label==="\\utilde"?.12:0,i=Qt({positionType:"top",positionData:t.height,children:[{type:"elem",elem:s,wrapperClasses:["svg-align"]},{type:"kern",size:r},{type:"elem",elem:t}]});return Ee(["mord","accentunder"],[i],e)},mathmlBuilder:(n,e)=>{var t=dg(n.label),s=new Re("munder",[mn(n.base,e),t]);return s.setAttribute("accentunder","true"),s}});var bf=n=>{var e=new Re("mpadded",n?[n]:[]);return e.setAttribute("width","+0.6em"),e.setAttribute("lspace","0.3em"),e};Ye({type:"xArrow",names:["\\xleftarrow","\\xrightarrow","\\xLeftarrow","\\xRightarrow","\\xleftrightarrow","\\xLeftrightarrow","\\xhookleftarrow","\\xhookrightarrow","\\xmapsto","\\xrightharpoondown","\\xrightharpoonup","\\xleftharpoondown","\\xleftharpoonup","\\xrightleftharpoons","\\xleftrightharpoons","\\xlongequal","\\xtwoheadrightarrow","\\xtwoheadleftarrow","\\xtofrom","\\xrightleftarrows","\\xrightequilibrium","\\xleftequilibrium","\\\\cdrightarrow","\\\\cdleftarrow","\\\\cdlongequal"],props:{numArgs:1,numOptionalArgs:1},handler(n,e,t){var{parser:s,funcName:r}=n;return{type:"xArrow",mode:s.mode,label:r,body:e[0],below:t[0]}},htmlBuilder(n,e){var t=e.style,s=e.havingStyle(t.sup()),r=Xc(tn(n.body,s,e),e),i=n.label.slice(0,2)==="\\x"?"x":"cd";r.classes.push(i+"-arrow-pad");var o;n.below&&(s=e.havingStyle(t.sub()),o=Xc(tn(n.below,s,e),e),o.classes.push(i+"-arrow-pad"));var a=pg(n,e),l=-e.fontMetrics().axisHeight+.5*a.height,c=-e.fontMetrics().axisHeight-.5*a.height-.111;(r.depth>.25||n.label==="\\xleftequilibrium")&&(c-=r.depth);var u;if(o){var h=-e.fontMetrics().axisHeight+o.height+.5*a.height+.111;u=Qt({positionType:"individualShift",children:[{type:"elem",elem:r,shift:c},{type:"elem",elem:a,shift:l},{type:"elem",elem:o,shift:h}]})}else u=Qt({positionType:"individualShift",children:[{type:"elem",elem:r,shift:c},{type:"elem",elem:a,shift:l}]});return u.children[0].children[0].children[1].classes.push("svg-align"),Ee(["mrel","x-arrow"],[u],e)},mathmlBuilder(n,e){var t=dg(n.label);t.setAttribute("minsize",n.label.charAt(0)==="x"?"1.75em":"3.0em");var s;if(n.body){var r=bf(mn(n.body,e));if(n.below){var i=bf(mn(n.below,e));s=new Re("munderover",[t,i,r])}else s=new Re("mover",[t,r])}else if(n.below){var o=bf(mn(n.below,e));s=new Re("munder",[t,o])}else s=bf(),s=new Re("mover",[t,s]);return s}});function DA(n,e){var t=ms(n.body,e,!0);return Ee([n.mclass],t,e)}function PA(n,e){var t,s=Or(n.body,e);return n.mclass==="minner"?t=new Re("mpadded",s):n.mclass==="mord"?n.isCharacterBox?(t=s[0],t.type="mi"):t=new Re("mi",s):(n.isCharacterBox?(t=s[0],t.type="mo"):t=new Re("mo",s),n.mclass==="mbin"?(t.attributes.lspace="0.22em",t.attributes.rspace="0.22em"):n.mclass==="mpunct"?(t.attributes.lspace="0em",t.attributes.rspace="0.17em"):n.mclass==="mopen"||n.mclass==="mclose"?(t.attributes.lspace="0em",t.attributes.rspace="0em"):n.mclass==="minner"&&(t.attributes.lspace="0.0556em",t.attributes.width="+0.1111em")),t}Ye({type:"mclass",names:["\\mathord","\\mathbin","\\mathrel","\\mathopen","\\mathclose","\\mathpunct","\\mathinner"],props:{numArgs:1,primitive:!0},handler(n,e){var{parser:t,funcName:s}=n,r=e[0];return{type:"mclass",mode:t.mode,mclass:"m"+s.slice(5),body:es(r),isCharacterBox:Po(r)}},htmlBuilder:DA,mathmlBuilder:PA});var gg=n=>{var e=n.type==="ordgroup"&&n.body.length?n.body[0]:n;return e.type==="atom"&&(e.family==="bin"||e.family==="rel")?"m"+e.family:"mord"};Ye({type:"mclass",names:["\\@binrel"],props:{numArgs:2},handler(n,e){var{parser:t}=n;return{type:"mclass",mode:t.mode,mclass:gg(e[0]),body:es(e[1]),isCharacterBox:Po(e[1])}}});Ye({type:"mclass",names:["\\stackrel","\\overset","\\underset"],props:{numArgs:2},handler(n,e){var{parser:t,funcName:s}=n,r=e[1],i=e[0],o;s!=="\\stackrel"?o=gg(r):o="mrel";var a={type:"op",mode:r.mode,limits:!0,alwaysHandleSupSub:!0,parentIsSupSub:!1,symbol:!1,suppressBaseShift:s!=="\\stackrel",body:es(r)},l={type:"supsub",mode:i.mode,base:a,sup:s==="\\underset"?null:i,sub:s==="\\underset"?i:null};return{type:"mclass",mode:t.mode,mclass:o,body:[l],isCharacterBox:Po(l)}},htmlBuilder:DA,mathmlBuilder:PA});Ye({type:"pmb",names:["\\pmb"],props:{numArgs:1,allowedInText:!0},handler(n,e){var{parser:t}=n;return{type:"pmb",mode:t.mode,mclass:gg(e[0]),body:es(e[0])}},htmlBuilder(n,e){var t=ms(n.body,e,!0),s=Ee([n.mclass],t,e);return s.style.textShadow="0.02em 0.01em 0.04px",s},mathmlBuilder(n,e){var t=Or(n.body,e),s=new Re("mstyle",t);return s.setAttribute("style","text-shadow: 0.02em 0.01em 0.04px"),s}});var Mge={">":"\\\\cdrightarrow","<":"\\\\cdleftarrow","=":"\\\\cdlongequal",A:"\\uparrow",V:"\\downarrow","|":"\\Vert",".":"no arrow"},CS=()=>({type:"styling",body:[],mode:"math",style:"display"}),_S=n=>n.type==="textord"&&n.text==="@",Nge=(n,e)=>(n.type==="mathord"||n.type==="atom")&&n.text===e;function $ge(n,e,t){var s=Mge[n];switch(s){case"\\\\cdrightarrow":case"\\\\cdleftarrow":return t.callFunction(s,[e[0]],[e[1]]);case"\\uparrow":case"\\downarrow":{var r=t.callFunction("\\\\cdleft",[e[0]],[]),i={type:"atom",text:s,mode:"math",family:"rel"},o=t.callFunction("\\Big",[i],[]),a=t.callFunction("\\\\cdright",[e[1]],[]),l={type:"ordgroup",mode:"math",body:[r,o,a]};return t.callFunction("\\\\cdparent",[l],[])}case"\\\\cdlongequal":return t.callFunction("\\\\cdlongequal",[],[]);case"\\Vert":{var c={type:"textord",text:"\\Vert",mode:"math"};return t.callFunction("\\Big",[c],[])}default:return{type:"textord",text:" ",mode:"math"}}}function Dge(n){var e=[];for(n.gullet.beginGroup(),n.gullet.macros.set("\\cr","\\\\\\relax"),n.gullet.beginGroup();;){e.push(n.parseExpression(!1,"\\\\")),n.gullet.endGroup(),n.gullet.beginGroup();var t=n.fetch().text;if(t==="&"||t==="\\\\")n.consume();else if(t==="\\end"){e[e.length-1].length===0&&e.pop();break}else throw new Ae("Expected \\\\ or \\cr or \\end",n.nextToken)}for(var s=[],r=[s],i=0;iAV".includes(c))for(var h=0;h<2;h++){for(var d=!0,p=l+1;pAV=|." after @',o[l]);var f=$ge(c,u,n),x={type:"styling",body:[f],mode:"math",style:"display"};s.push(x),a=CS()}i%2===0?s.push(a):s.shift(),s=[],r.push(s)}n.gullet.endGroup(),n.gullet.endGroup();var m=new Array(r[0].length).fill({type:"align",align:"c",pregap:.25,postgap:.25});return{type:"array",mode:"math",body:r,arraystretch:1,addJot:!0,rowGaps:[null],cols:m,colSeparationType:"CD",hLinesBeforeRow:new Array(r.length+1).fill([])}}Ye({type:"cdlabel",names:["\\\\cdleft","\\\\cdright"],props:{numArgs:1},handler(n,e){var{parser:t,funcName:s}=n;return{type:"cdlabel",mode:t.mode,side:s.slice(4),label:e[0]}},htmlBuilder(n,e){var t=e.havingStyle(e.style.sup()),s=Xc(tn(n.label,t,e),e);return s.classes.push("cd-label-"+n.side),s.style.bottom=Ne(.8-s.depth),s.height=0,s.depth=0,s},mathmlBuilder(n,e){var t=new Re("mrow",[mn(n.label,e)]);return t=new Re("mpadded",[t]),t.setAttribute("width","0"),n.side==="left"&&t.setAttribute("lspace","-1width"),t.setAttribute("voffset","0.7em"),t=new Re("mstyle",[t]),t.setAttribute("displaystyle","false"),t.setAttribute("scriptlevel","1"),t}});Ye({type:"cdlabelparent",names:["\\\\cdparent"],props:{numArgs:1},handler(n,e){var{parser:t}=n;return{type:"cdlabelparent",mode:t.mode,fragment:e[0]}},htmlBuilder(n,e){var t=Xc(tn(n.fragment,e),e);return t.classes.push("cd-vert-arrow"),t},mathmlBuilder(n,e){return new Re("mrow",[mn(n.fragment,e)])}});Ye({type:"textord",names:["\\@char"],props:{numArgs:1,allowedInText:!0},handler(n,e){for(var{parser:t}=n,s=Dt(e[0],"ordgroup"),r=s.body,i="",o=0;o=1114111)throw new Ae("\\@char with invalid code point "+i);return l<=65535?c=String.fromCharCode(l):(l-=65536,c=String.fromCharCode((l>>10)+55296,(l&1023)+56320)),{type:"textord",mode:t.mode,text:c}}});var LA=(n,e)=>{var t=ms(n.body,e.withColor(n.color),!1);return Fo(t)},FA=(n,e)=>{var t=Or(n.body,e.withColor(n.color)),s=new Re("mstyle",t);return s.setAttribute("mathcolor",n.color),s};Ye({type:"color",names:["\\textcolor"],props:{numArgs:2,allowedInText:!0,argTypes:["color","original"]},handler(n,e){var{parser:t}=n,s=Dt(e[0],"color-token").color,r=e[1];return{type:"color",mode:t.mode,color:s,body:es(r)}},htmlBuilder:LA,mathmlBuilder:FA});Ye({type:"color",names:["\\color"],props:{numArgs:1,allowedInText:!0,argTypes:["color"]},handler(n,e){var{parser:t,breakOnTokenText:s}=n,r=Dt(e[0],"color-token").color;t.gullet.macros.set("\\current@color",r);var i=t.parseExpression(!0,s);return{type:"color",mode:t.mode,color:r,body:i}},htmlBuilder:LA,mathmlBuilder:FA});Ye({type:"cr",names:["\\\\"],props:{numArgs:0,numOptionalArgs:0,allowedInText:!0},handler(n,e,t){var{parser:s}=n,r=s.gullet.future().text==="["?s.parseSizeGroup(!0):null,i=!s.settings.displayMode||!s.settings.useStrictBehavior("newLineInDisplayMode","In LaTeX, \\\\ or \\newline does nothing in display mode");return{type:"cr",mode:s.mode,newLine:i,size:r&&Dt(r,"size").value}},htmlBuilder(n,e){var t=Ee(["mspace"],[],e);return n.newLine&&(t.classes.push("newline"),n.size&&(t.style.marginTop=Ne(Dn(n.size,e)))),t},mathmlBuilder(n,e){var t=new Re("mspace");return n.newLine&&(t.setAttribute("linebreak","newline"),n.size&&t.setAttribute("height",Ne(Dn(n.size,e)))),t}});var Zx={"\\global":"\\global","\\long":"\\\\globallong","\\\\globallong":"\\\\globallong","\\def":"\\gdef","\\gdef":"\\gdef","\\edef":"\\xdef","\\xdef":"\\xdef","\\let":"\\\\globallet","\\futurelet":"\\\\globalfuture"},OA=n=>{var e=n.text;if(/^(?:[\\{}$&#^_]|EOF)$/.test(e))throw new Ae("Expected a control sequence",n);return e},Pge=n=>{var e=n.gullet.popToken();return e.text==="="&&(e=n.gullet.popToken(),e.text===" "&&(e=n.gullet.popToken())),e},zA=(n,e,t,s)=>{var r=n.gullet.macros.get(t.text);r==null&&(t.noexpand=!0,r={tokens:[t],numArgs:0,unexpandable:!n.gullet.isExpandable(t.text)}),n.gullet.macros.set(e,r,s)};Ye({type:"internal",names:["\\global","\\long","\\\\globallong"],props:{numArgs:0,allowedInText:!0},handler(n){var{parser:e,funcName:t}=n;e.consumeSpaces();var s=e.fetch();if(Zx[s.text])return(t==="\\global"||t==="\\\\globallong")&&(s.text=Zx[s.text]),Dt(e.parseFunction(),"internal");throw new Ae("Invalid token after macro prefix",s)}});Ye({type:"internal",names:["\\def","\\gdef","\\edef","\\xdef"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(n){var{parser:e,funcName:t}=n,s=e.gullet.popToken(),r=s.text;if(/^(?:[\\{}$&#^_]|EOF)$/.test(r))throw new Ae("Expected a control sequence",s);for(var i=0,o,a=[[]];e.gullet.future().text!=="{";)if(s=e.gullet.popToken(),s.text==="#"){if(e.gullet.future().text==="{"){o=e.gullet.future(),a[i].push("{");break}if(s=e.gullet.popToken(),!/^[1-9]$/.test(s.text))throw new Ae('Invalid argument number "'+s.text+'"');if(parseInt(s.text)!==i+1)throw new Ae('Argument number "'+s.text+'" out of order');i++,a.push([])}else{if(s.text==="EOF")throw new Ae("Expected a macro definition");a[i].push(s.text)}var{tokens:l}=e.gullet.consumeArg();return o&&l.unshift(o),(t==="\\edef"||t==="\\xdef")&&(l=e.gullet.expandTokens(l),l.reverse()),e.gullet.macros.set(r,{tokens:l,numArgs:i,delimiters:a},t===Zx[t]),{type:"internal",mode:e.mode}}});Ye({type:"internal",names:["\\let","\\\\globallet"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(n){var{parser:e,funcName:t}=n,s=OA(e.gullet.popToken());e.gullet.consumeSpaces();var r=Pge(e);return zA(e,s,r,t==="\\\\globallet"),{type:"internal",mode:e.mode}}});Ye({type:"internal",names:["\\futurelet","\\\\globalfuture"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(n){var{parser:e,funcName:t}=n,s=OA(e.gullet.popToken()),r=e.gullet.popToken(),i=e.gullet.popToken();return zA(e,s,i,t==="\\\\globalfuture"),e.gullet.pushToken(i),e.gullet.pushToken(r),{type:"internal",mode:e.mode}}});var Rh=function(e,t,s){var r=Rn.math[e]&&Rn.math[e].replace,i=gb(r||e,t,s);if(!i)throw new Error("Unsupported symbol "+e+" and font size "+t+".");return i},Sb=function(e,t,s,r){var i=s.havingBaseStyle(t),o=Ee(r.concat(i.sizingClasses(s)),[e],s),a=i.sizeMultiplier/s.sizeMultiplier;return o.height*=a,o.depth*=a,o.maxFontSize=i.sizeMultiplier,o},BA=function(e,t,s){var r=t.havingBaseStyle(s),i=(1-t.sizeMultiplier/r.sizeMultiplier)*t.fontMetrics().axisHeight;e.classes.push("delimcenter"),e.style.top=Ne(i),e.height-=i,e.depth+=i},Lge=function(e,t,s,r,i,o){var a=Ks(e,"Main-Regular",i,r),l=Sb(a,t,r,o);return BA(l,r,t),l},Fge=function(e,t,s,r){return Ks(e,"Size"+t+"-Regular",s,r)},UA=function(e,t,s,r,i,o){var a=Fge(e,t,i,r),l=Sb(Ee(["delimsizing","size"+t],[a],r),kt.TEXT,r,o);return s&&BA(l,r,kt.TEXT),l},N1=function(e,t,s){var r;t==="Size1-Regular"?r="delim-size1":r="delim-size4";var i=Ee(["delimsizinginner",r],[Ee([],[Ks(e,t,s)])]);return{type:"elem",elem:i}},$1=function(e,t,s){var r=Wi["Size4-Regular"][e.charCodeAt(0)]?Wi["Size4-Regular"][e.charCodeAt(0)][4]:Wi["Size1-Regular"][e.charCodeAt(0)][4],i=new ga("inner",Zme(e,Math.round(1e3*t))),o=new Mo([i],{width:Ne(r),height:Ne(t),style:"width:"+Ne(r),viewBox:"0 0 "+1e3*r+" "+Math.round(1e3*t),preserveAspectRatio:"xMinYMin"}),a=xa([],[o],s);return a.height=t,a.style.height=Ne(t),a.style.width=Ne(r),{type:"elem",elem:a}},Jx=.008,yf={type:"kern",size:-1*Jx},Oge=new Set(["|","\\lvert","\\rvert","\\vert"]),zge=new Set(["\\|","\\lVert","\\rVert","\\Vert"]),VA=function(e,t,s,r,i,o){var a,l,c,u,h="",d=0;a=c=u=e,l=null;var p="Size1-Regular";e==="\\uparrow"?c=u="⏐":e==="\\Uparrow"?c=u="‖":e==="\\downarrow"?a=c="⏐":e==="\\Downarrow"?a=c="‖":e==="\\updownarrow"?(a="\\uparrow",c="⏐",u="\\downarrow"):e==="\\Updownarrow"?(a="\\Uparrow",c="‖",u="\\Downarrow"):Oge.has(e)?(c="∣",h="vert",d=333):zge.has(e)?(c="∥",h="doublevert",d=556):e==="["||e==="\\lbrack"?(a="⎡",c="⎢",u="⎣",p="Size4-Regular",h="lbrack",d=667):e==="]"||e==="\\rbrack"?(a="⎤",c="⎥",u="⎦",p="Size4-Regular",h="rbrack",d=667):e==="\\lfloor"||e==="⌊"?(c=a="⎢",u="⎣",p="Size4-Regular",h="lfloor",d=667):e==="\\lceil"||e==="⌈"?(a="⎡",c=u="⎢",p="Size4-Regular",h="lceil",d=667):e==="\\rfloor"||e==="⌋"?(c=a="⎥",u="⎦",p="Size4-Regular",h="rfloor",d=667):e==="\\rceil"||e==="⌉"?(a="⎤",c=u="⎥",p="Size4-Regular",h="rceil",d=667):e==="("||e==="\\lparen"?(a="⎛",c="⎜",u="⎝",p="Size4-Regular",h="lparen",d=875):e===")"||e==="\\rparen"?(a="⎞",c="⎟",u="⎠",p="Size4-Regular",h="rparen",d=875):e==="\\{"||e==="\\lbrace"?(a="⎧",l="⎨",u="⎩",c="⎪",p="Size4-Regular"):e==="\\}"||e==="\\rbrace"?(a="⎫",l="⎬",u="⎭",c="⎪",p="Size4-Regular"):e==="\\lgroup"||e==="⟮"?(a="⎧",u="⎩",c="⎪",p="Size4-Regular"):e==="\\rgroup"||e==="⟯"?(a="⎫",u="⎭",c="⎪",p="Size4-Regular"):e==="\\lmoustache"||e==="⎰"?(a="⎧",u="⎭",c="⎪",p="Size4-Regular"):(e==="\\rmoustache"||e==="⎱")&&(a="⎫",u="⎩",c="⎪",p="Size4-Regular");var f=Rh(a,p,i),x=f.height+f.depth,m=Rh(c,p,i),g=m.height+m.depth,v=Rh(u,p,i),b=v.height+v.depth,y=0,w=1;if(l!==null){var C=Rh(l,p,i);y=C.height+C.depth,w=2}var T=x+b+y,E=Math.max(0,Math.ceil((t-T)/(w*g))),R=T+E*w*g,_=r.fontMetrics().axisHeight;s&&(_*=r.sizeMultiplier);var k=R/2-_,F=[];if(h.length>0){var B=R-x-b,M=Math.round(R*1e3),P=Jme(h,Math.round(B*1e3)),L=new ga(h,P),q=Ne(d/1e3),U=Ne(M/1e3),X=new Mo([L],{width:q,height:U,viewBox:"0 0 "+d+" "+M}),K=xa([],[X],r);K.height=M/1e3,K.style.width=q,K.style.height=U,F.push({type:"elem",elem:K})}else{if(F.push(N1(u,p,i)),F.push(yf),l===null){var J=R-x-b+2*Jx;F.push($1(c,J,r))}else{var ae=(R-x-b-y)/2+2*Jx;F.push($1(c,ae,r)),F.push(yf),F.push(N1(l,p,i)),F.push(yf),F.push($1(c,ae,r))}F.push(yf),F.push(N1(a,p,i))}var he=r.havingBaseStyle(kt.TEXT),j=Qt({positionType:"bottom",positionData:k,children:F});return Sb(Ee(["delimsizing","mult"],[j],he),kt.TEXT,r,o)},D1=80,P1=.08,L1=function(e,t,s,r,i){var o=Yme(e,r,s),a=new ga(e,o),l=new Mo([a],{width:"400em",height:Ne(t),viewBox:"0 0 400000 "+s,preserveAspectRatio:"xMinYMin slice"});return xa(["hide-tail"],[l],i)},Bge=function(e,t){var s=t.havingBaseSizing(),r=XA("\\surd",e*s.sizeMultiplier,qA,s),i=s.sizeMultiplier,o=Math.max(0,t.minRuleThickness-t.fontMetrics().sqrtRuleThickness),a,l=0,c=0,u=0,h;return r.type==="small"?(u=1e3+1e3*o+D1,e<1?i=1:e<1.4&&(i=.7),l=(1+o+P1)/i,c=(1+o)/i,a=L1("sqrtMain",l,u,o,t),a.style.minWidth="0.853em",h=.833/i):r.type==="large"?(u=(1e3+D1)*Dh[r.size],c=(Dh[r.size]+o)/i,l=(Dh[r.size]+o+P1)/i,a=L1("sqrtSize"+r.size,l,u,o,t),a.style.minWidth="1.02em",h=1/i):(l=e+o+P1,c=e+o,u=Math.floor(1e3*e+o)+D1,a=L1("sqrtTall",l,u,o,t),a.style.minWidth="0.742em",h=1.056),a.height=c,a.style.height=Ne(l),{span:a,advanceWidth:h,ruleWidth:(t.fontMetrics().sqrtRuleThickness+o)*i}},WA=new Set(["(","\\lparen",")","\\rparen","[","\\lbrack","]","\\rbrack","\\{","\\lbrace","\\}","\\rbrace","\\lfloor","\\rfloor","⌊","⌋","\\lceil","\\rceil","⌈","⌉","\\surd"]),Uge=new Set(["\\uparrow","\\downarrow","\\updownarrow","\\Uparrow","\\Downarrow","\\Updownarrow","|","\\|","\\vert","\\Vert","\\lvert","\\rvert","\\lVert","\\rVert","\\lgroup","\\rgroup","⟮","⟯","\\lmoustache","\\rmoustache","⎰","⎱"]),GA=new Set(["<",">","\\langle","\\rangle","/","\\backslash","\\lt","\\gt"]),Dh=[0,1.2,1.8,2.4,3],HA=function(e,t,s,r,i){if(e==="<"||e==="\\lt"||e==="⟨"?e="\\langle":(e===">"||e==="\\gt"||e==="⟩")&&(e="\\rangle"),WA.has(e)||GA.has(e))return UA(e,t,!1,s,r,i);if(Uge.has(e))return VA(e,Dh[t],!1,s,r,i);throw new Ae("Illegal delimiter: '"+e+"'")},Vge=[{type:"small",style:kt.SCRIPTSCRIPT},{type:"small",style:kt.SCRIPT},{type:"small",style:kt.TEXT},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4}],Wge=[{type:"small",style:kt.SCRIPTSCRIPT},{type:"small",style:kt.SCRIPT},{type:"small",style:kt.TEXT},{type:"stack"}],qA=[{type:"small",style:kt.SCRIPTSCRIPT},{type:"small",style:kt.SCRIPT},{type:"small",style:kt.TEXT},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4},{type:"stack"}],Gge=function(e){if(e.type==="small")return"Main-Regular";if(e.type==="large")return"Size"+e.size+"-Regular";if(e.type==="stack")return"Size4-Regular";var t=e.type;throw new Error("Add support for delim type '"+t+"' here.")},XA=function(e,t,s,r){for(var i=Math.min(2,3-r.style.size),o=i;ot)return a}return s[s.length-1]},Qx=function(e,t,s,r,i,o){e==="<"||e==="\\lt"||e==="⟨"?e="\\langle":(e===">"||e==="\\gt"||e==="⟩")&&(e="\\rangle");var a;GA.has(e)?a=Vge:WA.has(e)?a=qA:a=Wge;var l=XA(e,t,a,r);return l.type==="small"?Lge(e,l.style,s,r,i,o):l.type==="large"?UA(e,l.size,s,r,i,o):VA(e,t,s,r,i,o)},F1=function(e,t,s,r,i,o){var a=r.fontMetrics().axisHeight*r.sizeMultiplier,l=901,c=5/r.fontMetrics().ptPerEm,u=Math.max(t-a,s+a),h=Math.max(u/500*l,2*u-c);return Qx(e,h,!0,r,i,o)},TS={"\\bigl":{mclass:"mopen",size:1},"\\Bigl":{mclass:"mopen",size:2},"\\biggl":{mclass:"mopen",size:3},"\\Biggl":{mclass:"mopen",size:4},"\\bigr":{mclass:"mclose",size:1},"\\Bigr":{mclass:"mclose",size:2},"\\biggr":{mclass:"mclose",size:3},"\\Biggr":{mclass:"mclose",size:4},"\\bigm":{mclass:"mrel",size:1},"\\Bigm":{mclass:"mrel",size:2},"\\biggm":{mclass:"mrel",size:3},"\\Biggm":{mclass:"mrel",size:4},"\\big":{mclass:"mord",size:1},"\\Big":{mclass:"mord",size:2},"\\bigg":{mclass:"mord",size:3},"\\Bigg":{mclass:"mord",size:4}},Hge=new Set(["(","\\lparen",")","\\rparen","[","\\lbrack","]","\\rbrack","\\{","\\lbrace","\\}","\\rbrace","\\lfloor","\\rfloor","⌊","⌋","\\lceil","\\rceil","⌈","⌉","<",">","\\langle","⟨","\\rangle","⟩","\\lt","\\gt","\\lvert","\\rvert","\\lVert","\\rVert","\\lgroup","\\rgroup","⟮","⟯","\\lmoustache","\\rmoustache","⎰","⎱","/","\\backslash","|","\\vert","\\|","\\Vert","\\uparrow","\\Uparrow","\\downarrow","\\Downarrow","\\updownarrow","\\Updownarrow","."]);function xg(n,e){var t=mg(n);if(t&&Hge.has(t.text))return t;throw t?new Ae("Invalid delimiter '"+t.text+"' after '"+e.funcName+"'",n):new Ae("Invalid delimiter type '"+n.type+"'",n)}Ye({type:"delimsizing",names:["\\bigl","\\Bigl","\\biggl","\\Biggl","\\bigr","\\Bigr","\\biggr","\\Biggr","\\bigm","\\Bigm","\\biggm","\\Biggm","\\big","\\Big","\\bigg","\\Bigg"],props:{numArgs:1,argTypes:["primitive"]},handler:(n,e)=>{var t=xg(e[0],n);return{type:"delimsizing",mode:n.parser.mode,size:TS[n.funcName].size,mclass:TS[n.funcName].mclass,delim:t.text}},htmlBuilder:(n,e)=>n.delim==="."?Ee([n.mclass]):HA(n.delim,n.size,e,n.mode,[n.mclass]),mathmlBuilder:n=>{var e=[];n.delim!=="."&&e.push(ni(n.delim,n.mode));var t=new Re("mo",e);n.mclass==="mopen"||n.mclass==="mclose"?t.setAttribute("fence","true"):t.setAttribute("fence","false"),t.setAttribute("stretchy","true");var s=Ne(Dh[n.size]);return t.setAttribute("minsize",s),t.setAttribute("maxsize",s),t}});function IS(n){if(!n.body)throw new Error("Bug: The leftright ParseNode wasn't fully parsed.")}Ye({type:"leftright-right",names:["\\right"],props:{numArgs:1,primitive:!0},handler:(n,e)=>{var t=n.parser.gullet.macros.get("\\current@color");if(t&&typeof t!="string")throw new Ae("\\current@color set to non-string in \\right");return{type:"leftright-right",mode:n.parser.mode,delim:xg(e[0],n).text,color:t}}});Ye({type:"leftright",names:["\\left"],props:{numArgs:1,primitive:!0},handler:(n,e)=>{var t=xg(e[0],n),s=n.parser;++s.leftrightDepth;var r=s.parseExpression(!1);--s.leftrightDepth,s.expect("\\right",!1);var i=Dt(s.parseFunction(),"leftright-right");return{type:"leftright",mode:s.mode,body:r,left:t.text,right:i.delim,rightColor:i.color}},htmlBuilder:(n,e)=>{IS(n);for(var t=ms(n.body,e,!0,["mopen","mclose"]),s=0,r=0,i=!1,o=0;o{IS(n);var t=Or(n.body,e);if(n.left!=="."){var s=new Re("mo",[ni(n.left,n.mode)]);s.setAttribute("fence","true"),t.unshift(s)}if(n.right!=="."){var r=new Re("mo",[ni(n.right,n.mode)]);r.setAttribute("fence","true"),n.rightColor&&r.setAttribute("mathcolor",n.rightColor),t.push(r)}return bb(t)}});Ye({type:"middle",names:["\\middle"],props:{numArgs:1,primitive:!0},handler:(n,e)=>{var t=xg(e[0],n);if(!n.parser.leftrightDepth)throw new Ae("\\middle without preceding \\left",t);return{type:"middle",mode:n.parser.mode,delim:t.text}},htmlBuilder:(n,e)=>{var t;if(n.delim===".")t=ed(e,[]);else{t=HA(n.delim,1,e,n.mode,[]);var s={delim:n.delim,options:e};t.isMiddle=s}return t},mathmlBuilder:(n,e)=>{var t=n.delim==="\\vert"||n.delim==="|"?ni("|","text"):ni(n.delim,n.mode),s=new Re("mo",[t]);return s.setAttribute("fence","true"),s.setAttribute("lspace","0.05em"),s.setAttribute("rspace","0.05em"),s}});var vg=(n,e)=>{var t=Xc(tn(n.body,e),e),s=n.label.slice(1),r=e.sizeMultiplier,i,o=0,a=Po(n.body);if(s==="sout")i=Ee(["stretchy","sout"]),i.height=e.fontMetrics().defaultRuleThickness/r,o=-.5*e.fontMetrics().xHeight;else if(s==="phase"){var l=Dn({number:.6,unit:"pt"},e),c=Dn({number:.35,unit:"ex"},e),u=e.havingBaseSizing();r=r/u.sizeMultiplier;var h=t.height+t.depth+l+c;t.style.paddingLeft=Ne(h/2+l);var d=Math.floor(1e3*h*r),p=Kme(d),f=new Mo([new ga("phase",p)],{width:"400em",height:Ne(d/1e3),viewBox:"0 0 400000 "+d,preserveAspectRatio:"xMinYMin slice"});i=xa(["hide-tail"],[f],e),i.style.height=Ne(h),o=t.depth+l+c}else{/cancel/.test(s)?a||t.classes.push("cancel-pad"):s==="angl"?t.classes.push("anglpad"):t.classes.push("boxpad");var x=0,m=0,g=0;/box/.test(s)?(g=Math.max(e.fontMetrics().fboxrule,e.minRuleThickness),x=e.fontMetrics().fboxsep+(s==="colorbox"?0:g),m=x):s==="angl"?(g=Math.max(e.fontMetrics().defaultRuleThickness,e.minRuleThickness),x=4*g,m=Math.max(0,.25-t.depth)):(x=a?.2:0,m=x),i=Age(t,s,x,m,e),/fbox|boxed|fcolorbox/.test(s)?(i.style.borderStyle="solid",i.style.borderWidth=Ne(g)):s==="angl"&&g!==.049&&(i.style.borderTopWidth=Ne(g),i.style.borderRightWidth=Ne(g)),o=t.depth+m,n.backgroundColor&&(i.style.backgroundColor=n.backgroundColor,n.borderColor&&(i.style.borderColor=n.borderColor))}var v;if(n.backgroundColor)v=Qt({positionType:"individualShift",children:[{type:"elem",elem:i,shift:o},{type:"elem",elem:t,shift:0}]});else{var b=/cancel|phase/.test(s)?["svg-align"]:[];v=Qt({positionType:"individualShift",children:[{type:"elem",elem:t,shift:0},{type:"elem",elem:i,shift:o,wrapperClasses:b}]})}return/cancel/.test(s)&&(v.height=t.height,v.depth=t.depth),/cancel/.test(s)&&!a?Ee(["mord","cancel-lap"],[v],e):Ee(["mord"],[v],e)},bg=(n,e)=>{var t=0,s=new Re(n.label.includes("colorbox")?"mpadded":"menclose",[mn(n.body,e)]);switch(n.label){case"\\cancel":s.setAttribute("notation","updiagonalstrike");break;case"\\bcancel":s.setAttribute("notation","downdiagonalstrike");break;case"\\phase":s.setAttribute("notation","phasorangle");break;case"\\sout":s.setAttribute("notation","horizontalstrike");break;case"\\fbox":s.setAttribute("notation","box");break;case"\\angl":s.setAttribute("notation","actuarial");break;case"\\fcolorbox":case"\\colorbox":if(t=e.fontMetrics().fboxsep*e.fontMetrics().ptPerEm,s.setAttribute("width","+"+2*t+"pt"),s.setAttribute("height","+"+2*t+"pt"),s.setAttribute("lspace",t+"pt"),s.setAttribute("voffset",t+"pt"),n.label==="\\fcolorbox"){var r=Math.max(e.fontMetrics().fboxrule,e.minRuleThickness);s.setAttribute("style","border: "+Ne(r)+" solid "+n.borderColor)}break;case"\\xcancel":s.setAttribute("notation","updiagonalstrike downdiagonalstrike");break}return n.backgroundColor&&s.setAttribute("mathbackground",n.backgroundColor),s};Ye({type:"enclose",names:["\\colorbox"],props:{numArgs:2,allowedInText:!0,argTypes:["color","text"]},handler(n,e,t){var{parser:s,funcName:r}=n,i=Dt(e[0],"color-token").color,o=e[1];return{type:"enclose",mode:s.mode,label:r,backgroundColor:i,body:o}},htmlBuilder:vg,mathmlBuilder:bg});Ye({type:"enclose",names:["\\fcolorbox"],props:{numArgs:3,allowedInText:!0,argTypes:["color","color","text"]},handler(n,e,t){var{parser:s,funcName:r}=n,i=Dt(e[0],"color-token").color,o=Dt(e[1],"color-token").color,a=e[2];return{type:"enclose",mode:s.mode,label:r,backgroundColor:o,borderColor:i,body:a}},htmlBuilder:vg,mathmlBuilder:bg});Ye({type:"enclose",names:["\\fbox"],props:{numArgs:1,argTypes:["hbox"],allowedInText:!0},handler(n,e){var{parser:t}=n;return{type:"enclose",mode:t.mode,label:"\\fbox",body:e[0]}}});Ye({type:"enclose",names:["\\cancel","\\bcancel","\\xcancel","\\phase"],props:{numArgs:1},handler(n,e){var{parser:t,funcName:s}=n,r=e[0];return{type:"enclose",mode:t.mode,label:s,body:r}},htmlBuilder:vg,mathmlBuilder:bg});Ye({type:"enclose",names:["\\sout"],props:{numArgs:1,allowedInText:!0},handler(n,e){var{parser:t,funcName:s}=n;t.mode==="math"&&t.settings.reportNonstrict("mathVsSout","LaTeX's \\sout works only in text mode");var r=e[0];return{type:"enclose",mode:t.mode,label:s,body:r}},htmlBuilder:vg,mathmlBuilder:bg});Ye({type:"enclose",names:["\\angl"],props:{numArgs:1,argTypes:["hbox"],allowedInText:!1},handler(n,e){var{parser:t}=n;return{type:"enclose",mode:t.mode,label:"\\angl",body:e[0]}}});var KA={};function io(n){for(var{type:e,names:t,props:s,handler:r,htmlBuilder:i,mathmlBuilder:o}=n,a={type:e,numArgs:s.numArgs||0,allowedInText:!1,numOptionalArgs:0,handler:r},l=0;l{var e=n.parser.settings;if(!e.displayMode)throw new Ae("{"+n.envName+"} can be used only in display mode.")},qge=new Set(["gather","gather*"]);function Cb(n){if(!n.includes("ed"))return!n.includes("*")}function Ma(n,e,t){var{hskipBeforeAndAfter:s,addJot:r,cols:i,arraystretch:o,colSeparationType:a,autoTag:l,singleRow:c,emptySingleRow:u,maxNumCols:h,leqno:d}=e;if(n.gullet.beginGroup(),c||n.gullet.macros.set("\\cr","\\\\\\relax"),!o){var p=n.gullet.expandMacroAsText("\\arraystretch");if(p==null)o=1;else if(o=parseFloat(p),!o||o<0)throw new Ae("Invalid \\arraystretch: "+p)}n.gullet.beginGroup();var f=[],x=[f],m=[],g=[],v=l!=null?[]:void 0;function b(){l&&n.gullet.macros.set("\\@eqnsw","1",!0)}function y(){v&&(n.gullet.macros.get("\\df@tag")?(v.push(n.subparse([new Rr("\\df@tag")])),n.gullet.macros.set("\\df@tag",void 0,!0)):v.push(!!l&&n.gullet.macros.get("\\@eqnsw")==="1"))}for(b(),g.push(ES(n));;){var w=n.parseExpression(!1,c?"\\end":"\\\\");n.gullet.endGroup(),n.gullet.beginGroup();var C={type:"ordgroup",mode:n.mode,body:w};t&&(C={type:"styling",mode:n.mode,style:t,body:[C]}),f.push(C);var T=n.fetch().text;if(T==="&"){if(h&&f.length===h){if(c||a)throw new Ae("Too many tab characters: &",n.nextToken);n.settings.reportNonstrict("textEnv","Too few columns specified in the {array} column argument.")}n.consume()}else if(T==="\\end"){y(),f.length===1&&C.type==="styling"&&C.body.length===1&&C.body[0].type==="ordgroup"&&C.body[0].body.length===0&&(x.length>1||!u)&&x.pop(),g.length0&&(b+=.25),c.push({pos:b,isDashed:ot[xt]})}for(y(o[0]),s=0;s0&&(k+=v,Tot))for(s=0;s=a)){var ve=void 0;if(r>0||e.hskipBeforeAndAfter){var Ge,$e;ve=(Ge=($e=he)==null?void 0:$e.pregap)!=null?Ge:d,ve!==0&&(P=Ee(["arraycolsep"],[]),P.style.width=Ne(ve),M.push(P))}var te=[];for(s=0;s0){for(var ue=qc("hline",t,u),Se=qc("hdashline",t,u),ye=[{type:"elem",elem:$,shift:0}];c.length>0;){var Ce=c.pop(),Ze=Ce.pos-F;Ce.isDashed?ye.push({type:"elem",elem:Se,shift:Ze}):ye.push({type:"elem",elem:ue,shift:Ze})}$=Qt({positionType:"individualShift",children:ye})}if(q.length===0)return Ee(["mord"],[$],t);var Fe=Qt({positionType:"individualShift",children:q}),je=Ee(["tag"],[Fe],t);return Fo([$,je])},Xge={c:"center ",l:"left ",r:"right "},ao=function(e,t){for(var s=[],r=new Re("mtd",[],["mtr-glue"]),i=new Re("mtd",[],["mml-eqn-num"]),o=0;o0){var f=e.cols,x="",m=!1,g=0,v=f.length;f[0].type==="separator"&&(d+="top ",g=1),f[f.length-1].type==="separator"&&(d+="bottom ",v-=1);for(var b=g;b0?"left ":"",d+=R[R.length-1].length>0?"right ":"";for(var _=1;_0&&p&&(m=1),s[f]={type:"align",align:x,pregap:m,postgap:0}}return o.colSeparationType=p?"align":"alignat",o};io({type:"array",names:["array","darray"],props:{numArgs:1},handler(n,e){var t=mg(e[0]),s=t?[e[0]]:Dt(e[0],"ordgroup").body,r=s.map(function(o){var a=fg(o),l=a.text;if("lcr".includes(l))return{type:"align",align:l};if(l==="|")return{type:"separator",separator:"|"};if(l===":")return{type:"separator",separator:":"};throw new Ae("Unknown column alignment: "+l,o)}),i={cols:r,hskipBeforeAndAfter:!0,maxNumCols:r.length};return Ma(n.parser,i,_b(n.envName))},htmlBuilder:oo,mathmlBuilder:ao});io({type:"array",names:["matrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix","matrix*","pmatrix*","bmatrix*","Bmatrix*","vmatrix*","Vmatrix*"],props:{numArgs:0},handler(n){var e={matrix:null,pmatrix:["(",")"],bmatrix:["[","]"],Bmatrix:["\\{","\\}"],vmatrix:["|","|"],Vmatrix:["\\Vert","\\Vert"]}[n.envName.replace("*","")],t="c",s={hskipBeforeAndAfter:!1,cols:[{type:"align",align:t}]};if(n.envName.charAt(n.envName.length-1)==="*"){var r=n.parser;if(r.consumeSpaces(),r.fetch().text==="["){if(r.consume(),r.consumeSpaces(),t=r.fetch().text,!"lcr".includes(t))throw new Ae("Expected l or c or r",r.nextToken);r.consume(),r.consumeSpaces(),r.expect("]"),r.consume(),s.cols=[{type:"align",align:t}]}}var i=Ma(n.parser,s,_b(n.envName)),o=Math.max(0,...i.body.map(a=>a.length));return i.cols=new Array(o).fill({type:"align",align:t}),e?{type:"leftright",mode:n.mode,body:[i],left:e[0],right:e[1],rightColor:void 0}:i},htmlBuilder:oo,mathmlBuilder:ao});io({type:"array",names:["smallmatrix"],props:{numArgs:0},handler(n){var e={arraystretch:.5},t=Ma(n.parser,e,"script");return t.colSeparationType="small",t},htmlBuilder:oo,mathmlBuilder:ao});io({type:"array",names:["subarray"],props:{numArgs:1},handler(n,e){var t=mg(e[0]),s=t?[e[0]]:Dt(e[0],"ordgroup").body,r=s.map(function(a){var l=fg(a),c=l.text;if("lc".includes(c))return{type:"align",align:c};throw new Ae("Unknown column alignment: "+c,a)});if(r.length>1)throw new Ae("{subarray} can contain only one column");var i={cols:r,hskipBeforeAndAfter:!1,arraystretch:.5},o=Ma(n.parser,i,"script");if(o.body.length>0&&o.body[0].length>1)throw new Ae("{subarray} can contain only one column");return o},htmlBuilder:oo,mathmlBuilder:ao});io({type:"array",names:["cases","dcases","rcases","drcases"],props:{numArgs:0},handler(n){var e={arraystretch:1.2,cols:[{type:"align",align:"l",pregap:0,postgap:1},{type:"align",align:"l",pregap:0,postgap:0}]},t=Ma(n.parser,e,_b(n.envName));return{type:"leftright",mode:n.mode,body:[t],left:n.envName.includes("r")?".":"\\{",right:n.envName.includes("r")?"\\}":".",rightColor:void 0}},htmlBuilder:oo,mathmlBuilder:ao});io({type:"array",names:["align","align*","aligned","split"],props:{numArgs:0},handler:YA,htmlBuilder:oo,mathmlBuilder:ao});io({type:"array",names:["gathered","gather","gather*"],props:{numArgs:0},handler(n){qge.has(n.envName)&&yg(n);var e={cols:[{type:"align",align:"c"}],addJot:!0,colSeparationType:"gather",autoTag:Cb(n.envName),emptySingleRow:!0,leqno:n.parser.settings.leqno};return Ma(n.parser,e,"display")},htmlBuilder:oo,mathmlBuilder:ao});io({type:"array",names:["alignat","alignat*","alignedat"],props:{numArgs:1},handler:YA,htmlBuilder:oo,mathmlBuilder:ao});io({type:"array",names:["equation","equation*"],props:{numArgs:0},handler(n){yg(n);var e={autoTag:Cb(n.envName),emptySingleRow:!0,singleRow:!0,maxNumCols:1,leqno:n.parser.settings.leqno};return Ma(n.parser,e,"display")},htmlBuilder:oo,mathmlBuilder:ao});io({type:"array",names:["CD"],props:{numArgs:0},handler(n){return yg(n),Dge(n.parser)},htmlBuilder:oo,mathmlBuilder:ao});D("\\nonumber","\\gdef\\@eqnsw{0}");D("\\notag","\\nonumber");Ye({type:"text",names:["\\hline","\\hdashline"],props:{numArgs:0,allowedInText:!0,allowedInMath:!0},handler(n,e){throw new Ae(n.funcName+" valid only within array environment")}});var kS=KA;Ye({type:"environment",names:["\\begin","\\end"],props:{numArgs:1,argTypes:["text"]},handler(n,e){var{parser:t,funcName:s}=n,r=e[0];if(r.type!=="ordgroup")throw new Ae("Invalid environment name",r);for(var i="",o=0;o{var t=n.font,s=e.withFont(t);return tn(n.body,s)},JA=(n,e)=>{var t=n.font,s=e.withFont(t);return mn(n.body,s)},AS={"\\Bbb":"\\mathbb","\\bold":"\\mathbf","\\frak":"\\mathfrak","\\bm":"\\boldsymbol"};Ye({type:"font",names:["\\mathrm","\\mathit","\\mathbf","\\mathnormal","\\mathsfit","\\mathbb","\\mathcal","\\mathfrak","\\mathscr","\\mathsf","\\mathtt","\\Bbb","\\bold","\\frak"],props:{numArgs:1,allowedInArgument:!0},handler:(n,e)=>{var{parser:t,funcName:s}=n,r=v0(e[0]),i=s;return i in AS&&(i=AS[i]),{type:"font",mode:t.mode,font:i.slice(1),body:r}},htmlBuilder:ZA,mathmlBuilder:JA});Ye({type:"mclass",names:["\\boldsymbol","\\bm"],props:{numArgs:1},handler:(n,e)=>{var{parser:t}=n,s=e[0];return{type:"mclass",mode:t.mode,mclass:gg(s),body:[{type:"font",mode:t.mode,font:"boldsymbol",body:s}],isCharacterBox:Po(s)}}});Ye({type:"font",names:["\\rm","\\sf","\\tt","\\bf","\\it","\\cal"],props:{numArgs:0,allowedInText:!0},handler:(n,e)=>{var{parser:t,funcName:s,breakOnTokenText:r}=n,{mode:i}=t,o=t.parseExpression(!0,r),a="math"+s.slice(1);return{type:"font",mode:i,font:a,body:{type:"ordgroup",mode:t.mode,body:o}}},htmlBuilder:ZA,mathmlBuilder:JA});var Kge=(n,e)=>{var t=e.style,s=t.fracNum(),r=t.fracDen(),i;i=e.havingStyle(s);var o=tn(n.numer,i,e);if(n.continued){var a=8.5/e.fontMetrics().ptPerEm,l=3.5/e.fontMetrics().ptPerEm;o.height=o.height0?f=3*d:f=7*d,x=e.fontMetrics().denom1):(h>0?(p=e.fontMetrics().num2,f=d):(p=e.fontMetrics().num3,f=3*d),x=e.fontMetrics().denom2);var m;if(u){var v=e.fontMetrics().axisHeight;p-o.depth-(v+.5*h){var t=new Re("mfrac",[mn(n.numer,e),mn(n.denom,e)]);if(!n.hasBarLine)t.setAttribute("linethickness","0px");else if(n.barSize){var s=Dn(n.barSize,e);t.setAttribute("linethickness",Ne(s))}if(n.leftDelim!=null||n.rightDelim!=null){var r=[];if(n.leftDelim!=null){var i=new Re("mo",[new ts(n.leftDelim.replace("\\",""))]);i.setAttribute("fence","true"),r.push(i)}if(r.push(t),n.rightDelim!=null){var o=new Re("mo",[new ts(n.rightDelim.replace("\\",""))]);o.setAttribute("fence","true"),r.push(o)}return bb(r)}return t},QA=(n,e)=>{if(!e)return n;var t={type:"styling",mode:n.mode,style:e,body:[n]};return t};Ye({type:"genfrac",names:["\\cfrac","\\dfrac","\\frac","\\tfrac","\\dbinom","\\binom","\\tbinom","\\\\atopfrac","\\\\bracefrac","\\\\brackfrac"],props:{numArgs:2,allowedInArgument:!0},handler:(n,e)=>{var{parser:t,funcName:s}=n,r=e[0],i=e[1],o,a=null,l=null;switch(s){case"\\cfrac":case"\\dfrac":case"\\frac":case"\\tfrac":o=!0;break;case"\\\\atopfrac":o=!1;break;case"\\dbinom":case"\\binom":case"\\tbinom":o=!1,a="(",l=")";break;case"\\\\bracefrac":o=!1,a="\\{",l="\\}";break;case"\\\\brackfrac":o=!1,a="[",l="]";break;default:throw new Error("Unrecognized genfrac command")}var c=s==="\\cfrac",u=null;return c||s.startsWith("\\d")?u="display":s.startsWith("\\t")&&(u="text"),QA({type:"genfrac",mode:t.mode,numer:r,denom:i,continued:c,hasBarLine:o,leftDelim:a,rightDelim:l,barSize:null},u)},htmlBuilder:Kge,mathmlBuilder:jge});Ye({type:"infix",names:["\\over","\\choose","\\atop","\\brace","\\brack"],props:{numArgs:0,infix:!0},handler(n){var{parser:e,funcName:t,token:s}=n,r;switch(t){case"\\over":r="\\frac";break;case"\\choose":r="\\binom";break;case"\\atop":r="\\\\atopfrac";break;case"\\brace":r="\\\\bracefrac";break;case"\\brack":r="\\\\brackfrac";break;default:throw new Error("Unrecognized infix genfrac command")}return{type:"infix",mode:e.mode,replaceWith:r,token:s}}});var RS=["display","text","script","scriptscript"],MS=function(e){var t=null;return e.length>0&&(t=e,t=t==="."?null:t),t};Ye({type:"genfrac",names:["\\genfrac"],props:{numArgs:6,allowedInArgument:!0,argTypes:["math","math","size","text","math","math"]},handler(n,e){var{parser:t}=n,s=e[4],r=e[5],i=v0(e[0]),o=i.type==="atom"&&i.family==="open"?MS(i.text):null,a=v0(e[1]),l=a.type==="atom"&&a.family==="close"?MS(a.text):null,c=Dt(e[2],"size"),u,h=null;c.isBlank?u=!0:(h=c.value,u=h.number>0);var d=null,p=e[3];if(p.type==="ordgroup"){if(p.body.length>0){var f=Dt(p.body[0],"textord");d=RS[Number(f.text)]}}else p=Dt(p,"textord"),d=RS[Number(p.text)];return QA({type:"genfrac",mode:t.mode,numer:s,denom:r,continued:!1,hasBarLine:u,barSize:h,leftDelim:o,rightDelim:l},d)}});Ye({type:"infix",names:["\\above"],props:{numArgs:1,argTypes:["size"],infix:!0},handler(n,e){var{parser:t,funcName:s,token:r}=n;return{type:"infix",mode:t.mode,replaceWith:"\\\\abovefrac",size:Dt(e[0],"size").value,token:r}}});Ye({type:"genfrac",names:["\\\\abovefrac"],props:{numArgs:3,argTypes:["math","size","math"]},handler:(n,e)=>{var{parser:t,funcName:s}=n,r=e[0],i=Dt(e[1],"infix").size;if(!i)throw new Error("\\\\abovefrac expected size, but got "+String(i));var o=e[2],a=i.number>0;return{type:"genfrac",mode:t.mode,numer:r,denom:o,continued:!1,hasBarLine:a,barSize:i,leftDelim:null,rightDelim:null}}});var eR=(n,e)=>{var t=e.style,s,r;n.type==="supsub"?(s=n.sup?tn(n.sup,e.havingStyle(t.sup()),e):tn(n.sub,e.havingStyle(t.sub()),e),r=Dt(n.base,"horizBrace")):r=Dt(n,"horizBrace");var i=tn(r.base,e.havingBaseStyle(kt.DISPLAY)),o=pg(r,e),a;if(r.isOver?(a=Qt({positionType:"firstBaseline",children:[{type:"elem",elem:i},{type:"kern",size:.1},{type:"elem",elem:o}]}),a.children[0].children[0].children[1].classes.push("svg-align")):(a=Qt({positionType:"bottom",positionData:i.depth+.1+o.height,children:[{type:"elem",elem:o},{type:"kern",size:.1},{type:"elem",elem:i}]}),a.children[0].children[0].children[0].classes.push("svg-align")),s){var l=Ee(["minner",r.isOver?"mover":"munder"],[a],e);r.isOver?a=Qt({positionType:"firstBaseline",children:[{type:"elem",elem:l},{type:"kern",size:.2},{type:"elem",elem:s}]}):a=Qt({positionType:"bottom",positionData:l.depth+.2+s.height+s.depth,children:[{type:"elem",elem:s},{type:"kern",size:.2},{type:"elem",elem:l}]})}return Ee(["minner",r.isOver?"mover":"munder"],[a],e)},Yge=(n,e)=>{var t=dg(n.label);return new Re(n.isOver?"mover":"munder",[mn(n.base,e),t])};Ye({type:"horizBrace",names:["\\overbrace","\\underbrace","\\overbracket","\\underbracket"],props:{numArgs:1},handler(n,e){var{parser:t,funcName:s}=n;return{type:"horizBrace",mode:t.mode,label:s,isOver:s.includes("\\over"),base:e[0]}},htmlBuilder:eR,mathmlBuilder:Yge});Ye({type:"href",names:["\\href"],props:{numArgs:2,argTypes:["url","original"],allowedInText:!0},handler:(n,e)=>{var{parser:t}=n,s=e[1],r=Dt(e[0],"url").url;return t.settings.isTrusted({command:"\\href",url:r})?{type:"href",mode:t.mode,href:r,body:es(s)}:t.formatUnsupportedCmd("\\href")},htmlBuilder:(n,e)=>{var t=ms(n.body,e,!1);return pge(n.href,[],t,e)},mathmlBuilder:(n,e)=>{var t=va(n.body,e);return t instanceof Re||(t=new Re("mrow",[t])),t.setAttribute("href",n.href),t}});Ye({type:"href",names:["\\url"],props:{numArgs:1,argTypes:["url"],allowedInText:!0},handler:(n,e)=>{var{parser:t}=n,s=Dt(e[0],"url").url;if(!t.settings.isTrusted({command:"\\url",url:s}))return t.formatUnsupportedCmd("\\url");for(var r=[],i=0;i{var{parser:t,funcName:s,token:r}=n,i=Dt(e[0],"raw").string,o=e[1];t.settings.strict&&t.settings.reportNonstrict("htmlExtension","HTML extension is disabled on strict mode");var a,l={};switch(s){case"\\htmlClass":l.class=i,a={command:"\\htmlClass",class:i};break;case"\\htmlId":l.id=i,a={command:"\\htmlId",id:i};break;case"\\htmlStyle":l.style=i,a={command:"\\htmlStyle",style:i};break;case"\\htmlData":{for(var c=i.split(","),u=0;u{var t=ms(n.body,e,!1),s=["enclosing"];n.attributes.class&&s.push(...n.attributes.class.trim().split(/\s+/));var r=Ee(s,t,e);for(var i in n.attributes)i!=="class"&&n.attributes.hasOwnProperty(i)&&r.setAttribute(i,n.attributes[i]);return r},mathmlBuilder:(n,e)=>va(n.body,e)});Ye({type:"htmlmathml",names:["\\html@mathml"],props:{numArgs:2,allowedInArgument:!0,allowedInText:!0},handler:(n,e)=>{var{parser:t}=n;return{type:"htmlmathml",mode:t.mode,html:es(e[0]),mathml:es(e[1])}},htmlBuilder:(n,e)=>{var t=ms(n.html,e,!1);return Fo(t)},mathmlBuilder:(n,e)=>va(n.mathml,e)});var O1=function(e){if(/^[-+]? *(\d+(\.\d*)?|\.\d+)$/.test(e))return{number:+e,unit:"bp"};var t=/([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(e);if(!t)throw new Ae("Invalid size: '"+e+"' in \\includegraphics");var s={number:+(t[1]+t[2]),unit:t[3]};if(!xA(s))throw new Ae("Invalid unit: '"+s.unit+"' in \\includegraphics.");return s};Ye({type:"includegraphics",names:["\\includegraphics"],props:{numArgs:1,numOptionalArgs:1,argTypes:["raw","url"],allowedInText:!1},handler:(n,e,t)=>{var{parser:s}=n,r={number:0,unit:"em"},i={number:.9,unit:"em"},o={number:0,unit:"em"},a="";if(t[0])for(var l=Dt(t[0],"raw").string,c=l.split(","),u=0;u{var t=Dn(n.height,e),s=0;n.totalheight.number>0&&(s=Dn(n.totalheight,e)-t);var r=0;n.width.number>0&&(r=Dn(n.width,e));var i={height:Ne(t+s)};r>0&&(i.width=Ne(r)),s>0&&(i.verticalAlign=Ne(-s));var o=new tge(n.src,n.alt,i);return o.height=t,o.depth=s,o},mathmlBuilder:(n,e)=>{var t=new Re("mglyph",[]);t.setAttribute("alt",n.alt);var s=Dn(n.height,e),r=0;if(n.totalheight.number>0&&(r=Dn(n.totalheight,e)-s,t.setAttribute("valign",Ne(-r))),t.setAttribute("height",Ne(s+r)),n.width.number>0){var i=Dn(n.width,e);t.setAttribute("width",Ne(i))}return t.setAttribute("src",n.src),t}});Ye({type:"kern",names:["\\kern","\\mkern","\\hskip","\\mskip"],props:{numArgs:1,argTypes:["size"],primitive:!0,allowedInText:!0},handler(n,e){var{parser:t,funcName:s}=n,r=Dt(e[0],"size");if(t.settings.strict){var i=s[1]==="m",o=r.value.unit==="mu";i?(o||t.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+s+" supports only mu units, "+("not "+r.value.unit+" units")),t.mode!=="math"&&t.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+s+" works only in math mode")):o&&t.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+s+" doesn't support mu units")}return{type:"kern",mode:t.mode,dimension:r.value}},htmlBuilder(n,e){return CA(n.dimension,e)},mathmlBuilder(n,e){var t=Dn(n.dimension,e);return new AA(t)}});Ye({type:"lap",names:["\\mathllap","\\mathrlap","\\mathclap"],props:{numArgs:1,allowedInText:!0},handler:(n,e)=>{var{parser:t,funcName:s}=n,r=e[0];return{type:"lap",mode:t.mode,alignment:s.slice(5),body:r}},htmlBuilder:(n,e)=>{var t;n.alignment==="clap"?(t=Ee([],[tn(n.body,e)]),t=Ee(["inner"],[t],e)):t=Ee(["inner"],[tn(n.body,e)]);var s=Ee(["fix"],[]),r=Ee([n.alignment],[t,s],e),i=Ee(["strut"]);return i.style.height=Ne(r.height+r.depth),r.depth&&(i.style.verticalAlign=Ne(-r.depth)),r.children.unshift(i),r=Ee(["thinbox"],[r],e),Ee(["mord","vbox"],[r],e)},mathmlBuilder:(n,e)=>{var t=new Re("mpadded",[mn(n.body,e)]);if(n.alignment!=="rlap"){var s=n.alignment==="llap"?"-1":"-0.5";t.setAttribute("lspace",s+"width")}return t.setAttribute("width","0px"),t}});Ye({type:"styling",names:["\\(","$"],props:{numArgs:0,allowedInText:!0,allowedInMath:!1},handler(n,e){var{funcName:t,parser:s}=n,r=s.mode;s.switchMode("math");var i=t==="\\("?"\\)":"$",o=s.parseExpression(!1,i);return s.expect(i),s.switchMode(r),{type:"styling",mode:s.mode,style:"text",body:o}}});Ye({type:"text",names:["\\)","\\]"],props:{numArgs:0,allowedInText:!0,allowedInMath:!1},handler(n,e){throw new Ae("Mismatched "+n.funcName)}});var NS=(n,e)=>{switch(e.style.size){case kt.DISPLAY.size:return n.display;case kt.TEXT.size:return n.text;case kt.SCRIPT.size:return n.script;case kt.SCRIPTSCRIPT.size:return n.scriptscript;default:return n.text}};Ye({type:"mathchoice",names:["\\mathchoice"],props:{numArgs:4,primitive:!0},handler:(n,e)=>{var{parser:t}=n;return{type:"mathchoice",mode:t.mode,display:es(e[0]),text:es(e[1]),script:es(e[2]),scriptscript:es(e[3])}},htmlBuilder:(n,e)=>{var t=NS(n,e),s=ms(t,e,!1);return Fo(s)},mathmlBuilder:(n,e)=>{var t=NS(n,e);return va(t,e)}});var tR=(n,e,t,s,r,i,o)=>{n=Ee([],[n]);var a=t&&Po(t),l,c;if(e){var u=tn(e,s.havingStyle(r.sup()),s);c={elem:u,kern:Math.max(s.fontMetrics().bigOpSpacing1,s.fontMetrics().bigOpSpacing3-u.depth)}}if(t){var h=tn(t,s.havingStyle(r.sub()),s);l={elem:h,kern:Math.max(s.fontMetrics().bigOpSpacing2,s.fontMetrics().bigOpSpacing4-h.height)}}var d;if(c&&l){var p=s.fontMetrics().bigOpSpacing5+l.elem.height+l.elem.depth+l.kern+n.depth+o;d=Qt({positionType:"bottom",positionData:p,children:[{type:"kern",size:s.fontMetrics().bigOpSpacing5},{type:"elem",elem:l.elem,marginLeft:Ne(-i)},{type:"kern",size:l.kern},{type:"elem",elem:n},{type:"kern",size:c.kern},{type:"elem",elem:c.elem,marginLeft:Ne(i)},{type:"kern",size:s.fontMetrics().bigOpSpacing5}]})}else if(l){var f=n.height-o;d=Qt({positionType:"top",positionData:f,children:[{type:"kern",size:s.fontMetrics().bigOpSpacing5},{type:"elem",elem:l.elem,marginLeft:Ne(-i)},{type:"kern",size:l.kern},{type:"elem",elem:n}]})}else if(c){var x=n.depth+o;d=Qt({positionType:"bottom",positionData:x,children:[{type:"elem",elem:n},{type:"kern",size:c.kern},{type:"elem",elem:c.elem,marginLeft:Ne(i)},{type:"kern",size:s.fontMetrics().bigOpSpacing5}]})}else return n;var m=[d];if(l&&i!==0&&!a){var g=Ee(["mspace"],[],s);g.style.marginRight=Ne(i),m.unshift(g)}return Ee(["mop","op-limits"],m,s)},nR=new Set(["\\smallint"]),hh=(n,e)=>{var t,s,r=!1,i;n.type==="supsub"?(t=n.sup,s=n.sub,i=Dt(n.base,"op"),r=!0):i=Dt(n,"op");var o=e.style,a=!1;o.size===kt.DISPLAY.size&&i.symbol&&!nR.has(i.name)&&(a=!0);var l;if(i.symbol){var c=a?"Size2-Regular":"Size1-Regular",u="";if((i.name==="\\oiint"||i.name==="\\oiiint")&&(u=i.name.slice(1),i.name=u==="oiint"?"\\iint":"\\iiint"),l=Ks(i.name,c,"math",e,["mop","op-symbol",a?"large-op":"small-op"]),u.length>0){var h=l.italic,d=TA(u+"Size"+(a?"2":"1"),e);l=Qt({positionType:"individualShift",children:[{type:"elem",elem:l,shift:0},{type:"elem",elem:d,shift:a?.08:0}]}),i.name="\\"+u,l.classes.unshift("mop"),l.italic=h}}else if(i.body){var p=ms(i.body,e,!0);p.length===1&&p[0]instanceof Nr?(l=p[0],l.classes[0]="mop"):l=Ee(["mop"],p,e)}else{for(var f=[],x=1;x{var t;if(n.symbol)t=new Re("mo",[ni(n.name,n.mode)]),nR.has(n.name)&&t.setAttribute("largeop","false");else if(n.body)t=new Re("mo",Or(n.body,e));else{t=new Re("mi",[new ts(n.name.slice(1))]);var s=new Re("mo",[ni("⁡","text")]);n.parentIsSupSub?t=new Re("mrow",[t,s]):t=kA([t,s])}return t},Zge={"∏":"\\prod","∐":"\\coprod","∑":"\\sum","⋀":"\\bigwedge","⋁":"\\bigvee","⋂":"\\bigcap","⋃":"\\bigcup","⨀":"\\bigodot","⨁":"\\bigoplus","⨂":"\\bigotimes","⨄":"\\biguplus","⨆":"\\bigsqcup"};Ye({type:"op",names:["\\coprod","\\bigvee","\\bigwedge","\\biguplus","\\bigcap","\\bigcup","\\intop","\\prod","\\sum","\\bigotimes","\\bigoplus","\\bigodot","\\bigsqcup","\\smallint","∏","∐","∑","⋀","⋁","⋂","⋃","⨀","⨁","⨂","⨄","⨆"],props:{numArgs:0},handler:(n,e)=>{var{parser:t,funcName:s}=n,r=s;return r.length===1&&(r=Zge[r]),{type:"op",mode:t.mode,limits:!0,parentIsSupSub:!1,symbol:!0,name:r}},htmlBuilder:hh,mathmlBuilder:kp});Ye({type:"op",names:["\\mathop"],props:{numArgs:1,primitive:!0},handler:(n,e)=>{var{parser:t}=n,s=e[0];return{type:"op",mode:t.mode,limits:!1,parentIsSupSub:!1,symbol:!1,body:es(s)}},htmlBuilder:hh,mathmlBuilder:kp});var Jge={"∫":"\\int","∬":"\\iint","∭":"\\iiint","∮":"\\oint","∯":"\\oiint","∰":"\\oiiint"};Ye({type:"op",names:["\\arcsin","\\arccos","\\arctan","\\arctg","\\arcctg","\\arg","\\ch","\\cos","\\cosec","\\cosh","\\cot","\\cotg","\\coth","\\csc","\\ctg","\\cth","\\deg","\\dim","\\exp","\\hom","\\ker","\\lg","\\ln","\\log","\\sec","\\sin","\\sinh","\\sh","\\tan","\\tanh","\\tg","\\th"],props:{numArgs:0},handler(n){var{parser:e,funcName:t}=n;return{type:"op",mode:e.mode,limits:!1,parentIsSupSub:!1,symbol:!1,name:t}},htmlBuilder:hh,mathmlBuilder:kp});Ye({type:"op",names:["\\det","\\gcd","\\inf","\\lim","\\max","\\min","\\Pr","\\sup"],props:{numArgs:0},handler(n){var{parser:e,funcName:t}=n;return{type:"op",mode:e.mode,limits:!0,parentIsSupSub:!1,symbol:!1,name:t}},htmlBuilder:hh,mathmlBuilder:kp});Ye({type:"op",names:["\\int","\\iint","\\iiint","\\oint","\\oiint","\\oiiint","∫","∬","∭","∮","∯","∰"],props:{numArgs:0,allowedInArgument:!0},handler(n){var{parser:e,funcName:t}=n,s=t;return s.length===1&&(s=Jge[s]),{type:"op",mode:e.mode,limits:!1,parentIsSupSub:!1,symbol:!0,name:s}},htmlBuilder:hh,mathmlBuilder:kp});var sR=(n,e)=>{var t,s,r=!1,i;n.type==="supsub"?(t=n.sup,s=n.sub,i=Dt(n.base,"operatorname"),r=!0):i=Dt(n,"operatorname");var o;if(i.body.length>0){for(var a=i.body.map(h=>{var d="text"in h?h.text:void 0;return typeof d=="string"?{type:"textord",mode:h.mode,text:d}:h}),l=ms(a,e.withFont("mathrm"),!0),c=0;c{for(var t=Or(n.body,e.withFont("mathrm")),s=!0,r=0;ru.toText()).join("");t=[new ts(a)]}var l=new Re("mi",t);l.setAttribute("mathvariant","normal");var c=new Re("mo",[ni("⁡","text")]);return n.parentIsSupSub?new Re("mrow",[l,c]):kA([l,c])};Ye({type:"operatorname",names:["\\operatorname@","\\operatornamewithlimits"],props:{numArgs:1},handler:(n,e)=>{var{parser:t,funcName:s}=n,r=e[0];return{type:"operatorname",mode:t.mode,body:es(r),alwaysHandleSupSub:s==="\\operatornamewithlimits",limits:!1,parentIsSupSub:!1}},htmlBuilder:sR,mathmlBuilder:Qge});D("\\operatorname","\\@ifstar\\operatornamewithlimits\\operatorname@");ql({type:"ordgroup",htmlBuilder(n,e){return n.semisimple?Fo(ms(n.body,e,!1)):Ee(["mord"],ms(n.body,e,!0),e)},mathmlBuilder(n,e){return va(n.body,e,!0)}});Ye({type:"overline",names:["\\overline"],props:{numArgs:1},handler(n,e){var{parser:t}=n,s=e[0];return{type:"overline",mode:t.mode,body:s}},htmlBuilder(n,e){var t=tn(n.body,e.havingCrampedStyle()),s=qc("overline-line",e),r=e.fontMetrics().defaultRuleThickness,i=Qt({positionType:"firstBaseline",children:[{type:"elem",elem:t},{type:"kern",size:3*r},{type:"elem",elem:s},{type:"kern",size:r}]});return Ee(["mord","overline"],[i],e)},mathmlBuilder(n,e){var t=new Re("mo",[new ts("‾")]);t.setAttribute("stretchy","true");var s=new Re("mover",[mn(n.body,e),t]);return s.setAttribute("accent","true"),s}});Ye({type:"phantom",names:["\\phantom"],props:{numArgs:1,allowedInText:!0},handler:(n,e)=>{var{parser:t}=n,s=e[0];return{type:"phantom",mode:t.mode,body:es(s)}},htmlBuilder:(n,e)=>{var t=ms(n.body,e.withPhantom(),!1);return Fo(t)},mathmlBuilder:(n,e)=>{var t=Or(n.body,e);return new Re("mphantom",t)}});D("\\hphantom","\\smash{\\phantom{#1}}");Ye({type:"vphantom",names:["\\vphantom"],props:{numArgs:1,allowedInText:!0},handler:(n,e)=>{var{parser:t}=n,s=e[0];return{type:"vphantom",mode:t.mode,body:s}},htmlBuilder:(n,e)=>{var t=Ee(["inner"],[tn(n.body,e.withPhantom())]),s=Ee(["fix"],[]);return Ee(["mord","rlap"],[t,s],e)},mathmlBuilder:(n,e)=>{var t=Or(es(n.body),e),s=new Re("mphantom",t),r=new Re("mpadded",[s]);return r.setAttribute("width","0px"),r}});Ye({type:"raisebox",names:["\\raisebox"],props:{numArgs:2,argTypes:["size","hbox"],allowedInText:!0},handler(n,e){var{parser:t}=n,s=Dt(e[0],"size").value,r=e[1];return{type:"raisebox",mode:t.mode,dy:s,body:r}},htmlBuilder(n,e){var t=tn(n.body,e),s=Dn(n.dy,e);return Qt({positionType:"shift",positionData:-s,children:[{type:"elem",elem:t}]})},mathmlBuilder(n,e){var t=new Re("mpadded",[mn(n.body,e)]),s=n.dy.number+n.dy.unit;return t.setAttribute("voffset",s),t}});Ye({type:"internal",names:["\\relax"],props:{numArgs:0,allowedInText:!0,allowedInArgument:!0},handler(n){var{parser:e}=n;return{type:"internal",mode:e.mode}}});Ye({type:"rule",names:["\\rule"],props:{numArgs:2,numOptionalArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:["size","size","size"]},handler(n,e,t){var{parser:s}=n,r=t[0],i=Dt(e[0],"size"),o=Dt(e[1],"size");return{type:"rule",mode:s.mode,shift:r&&Dt(r,"size").value,width:i.value,height:o.value}},htmlBuilder(n,e){var t=Ee(["mord","rule"],[],e),s=Dn(n.width,e),r=Dn(n.height,e),i=n.shift?Dn(n.shift,e):0;return t.style.borderRightWidth=Ne(s),t.style.borderTopWidth=Ne(r),t.style.bottom=Ne(i),t.width=s,t.height=r+i,t.depth=-i,t.maxFontSize=r*1.125*e.sizeMultiplier,t},mathmlBuilder(n,e){var t=Dn(n.width,e),s=Dn(n.height,e),r=n.shift?Dn(n.shift,e):0,i=e.color&&e.getColor()||"black",o=new Re("mspace");o.setAttribute("mathbackground",i),o.setAttribute("width",Ne(t)),o.setAttribute("height",Ne(s));var a=new Re("mpadded",[o]);return r>=0?a.setAttribute("height",Ne(r)):(a.setAttribute("height",Ne(r)),a.setAttribute("depth",Ne(-r))),a.setAttribute("voffset",Ne(r)),a}});function rR(n,e,t){for(var s=ms(n,e,!1),r=e.sizeMultiplier/t.sizeMultiplier,i=0;i{var t=e.havingSize(n.size);return rR(n.body,t,e)};Ye({type:"sizing",names:$S,props:{numArgs:0,allowedInText:!0},handler:(n,e)=>{var{breakOnTokenText:t,funcName:s,parser:r}=n,i=r.parseExpression(!1,t);return{type:"sizing",mode:r.mode,size:$S.indexOf(s)+1,body:i}},htmlBuilder:e1e,mathmlBuilder:(n,e)=>{var t=e.havingSize(n.size),s=Or(n.body,t),r=new Re("mstyle",s);return r.setAttribute("mathsize",Ne(t.sizeMultiplier)),r}});Ye({type:"smash",names:["\\smash"],props:{numArgs:1,numOptionalArgs:1,allowedInText:!0},handler:(n,e,t)=>{var{parser:s}=n,r=!1,i=!1,o=t[0]&&Dt(t[0],"ordgroup");if(o)for(var a="",l=0;l{var t=Ee([],[tn(n.body,e)]);if(!n.smashHeight&&!n.smashDepth)return t;if(n.smashHeight&&(t.height=0),n.smashDepth&&(t.depth=0),n.smashHeight&&n.smashDepth)return Ee(["mord","smash"],[t],e);if(t.children)for(var s=0;s{var t=new Re("mpadded",[mn(n.body,e)]);return n.smashHeight&&t.setAttribute("height","0px"),n.smashDepth&&t.setAttribute("depth","0px"),t}});Ye({type:"sqrt",names:["\\sqrt"],props:{numArgs:1,numOptionalArgs:1},handler(n,e,t){var{parser:s}=n,r=t[0],i=e[0];return{type:"sqrt",mode:s.mode,body:i,index:r}},htmlBuilder(n,e){var t=tn(n.body,e.havingCrampedStyle());t.height===0&&(t.height=e.fontMetrics().xHeight),t=Xc(t,e);var s=e.fontMetrics(),r=s.defaultRuleThickness,i=r;e.style.idt.height+t.depth+o&&(o=(o+h-t.height-t.depth)/2);var d=l.height-t.height-o-c;t.style.paddingLeft=Ne(u);var p=Qt({positionType:"firstBaseline",children:[{type:"elem",elem:t,wrapperClasses:["svg-align"]},{type:"kern",size:-(t.height+d)},{type:"elem",elem:l},{type:"kern",size:c}]});if(n.index){var f=e.havingStyle(kt.SCRIPTSCRIPT),x=tn(n.index,f,e),m=.6*(p.height-p.depth),g=Qt({positionType:"shift",positionData:-m,children:[{type:"elem",elem:x}]}),v=Ee(["root"],[g]);return Ee(["mord","sqrt"],[v,p],e)}else return Ee(["mord","sqrt"],[p],e)},mathmlBuilder(n,e){var{body:t,index:s}=n;return s?new Re("mroot",[mn(t,e),mn(s,e)]):new Re("msqrt",[mn(t,e)])}});var DS={display:kt.DISPLAY,text:kt.TEXT,script:kt.SCRIPT,scriptscript:kt.SCRIPTSCRIPT};Ye({type:"styling",names:["\\displaystyle","\\textstyle","\\scriptstyle","\\scriptscriptstyle"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(n,e){var{breakOnTokenText:t,funcName:s,parser:r}=n,i=r.parseExpression(!0,t),o=s.slice(1,s.length-5);return{type:"styling",mode:r.mode,style:o,body:i}},htmlBuilder(n,e){var t=DS[n.style],s=e.havingStyle(t).withFont("");return rR(n.body,s,e)},mathmlBuilder(n,e){var t=DS[n.style],s=e.havingStyle(t),r=Or(n.body,s),i=new Re("mstyle",r),o={display:["0","true"],text:["0","false"],script:["1","false"],scriptscript:["2","false"]},a=o[n.style];return i.setAttribute("scriptlevel",a[0]),i.setAttribute("displaystyle",a[1]),i}});var t1e=function(e,t){var s=e.base;if(s)if(s.type==="op"){var r=s.limits&&(t.style.size===kt.DISPLAY.size||s.alwaysHandleSupSub);return r?hh:null}else if(s.type==="operatorname"){var i=s.alwaysHandleSupSub&&(t.style.size===kt.DISPLAY.size||s.limits);return i?sR:null}else{if(s.type==="accent")return Po(s.base)?wb:null;if(s.type==="horizBrace"){var o=!e.sub;return o===s.isOver?eR:null}else return null}else return null};ql({type:"supsub",htmlBuilder(n,e){var t=t1e(n,e);if(t)return t(n,e);var{base:s,sup:r,sub:i}=n,o=tn(s,e),a,l,c=e.fontMetrics(),u=0,h=0,d=s&&Po(s);if(r){var p=e.havingStyle(e.style.sup());a=tn(r,p,e),d||(u=o.height-p.fontMetrics().supDrop*p.sizeMultiplier/e.sizeMultiplier)}if(i){var f=e.havingStyle(e.style.sub());l=tn(i,f,e),d||(h=o.depth+f.fontMetrics().subDrop*f.sizeMultiplier/e.sizeMultiplier)}var x;e.style===kt.DISPLAY?x=c.sup1:e.style.cramped?x=c.sup3:x=c.sup2;var m=e.sizeMultiplier,g=Ne(.5/c.ptPerEm/m),v=null;if(l){var b=n.base&&n.base.type==="op"&&n.base.name&&(n.base.name==="\\oiint"||n.base.name==="\\oiiint");(o instanceof Nr||b)&&(v=Ne(-o.italic))}var y;if(a&&l){u=Math.max(u,x,a.depth+.25*c.xHeight),h=Math.max(h,c.sub2);var w=c.defaultRuleThickness,C=4*w;if(u-a.depth-(l.height-h)0&&(u+=T,h-=T)}var E=[{type:"elem",elem:l,shift:h,marginRight:g,marginLeft:v},{type:"elem",elem:a,shift:-u,marginRight:g}];y=Qt({positionType:"individualShift",children:E})}else if(l){h=Math.max(h,c.sub1,l.height-.8*c.xHeight);var R=[{type:"elem",elem:l,marginLeft:v,marginRight:g}];y=Qt({positionType:"shift",positionData:h,children:R})}else if(a)u=Math.max(u,x,a.depth+.25*c.xHeight),y=Qt({positionType:"shift",positionData:-u,children:[{type:"elem",elem:a,marginRight:g}]});else throw new Error("supsub must have either sup or sub.");var _=jx(o,"right")||"mord";return Ee([_],[o,Ee(["msupsub"],[y])],e)},mathmlBuilder(n,e){var t=!1,s,r;n.base&&n.base.type==="horizBrace"&&(r=!!n.sup,r===n.base.isOver&&(t=!0,s=n.base.isOver)),n.base&&(n.base.type==="op"||n.base.type==="operatorname")&&(n.base.parentIsSupSub=!0);var i=[mn(n.base,e)];n.sub&&i.push(mn(n.sub,e)),n.sup&&i.push(mn(n.sup,e));var o;if(t)o=s?"mover":"munder";else if(n.sub)if(n.sup){var c=n.base;c&&c.type==="op"&&c.limits&&e.style===kt.DISPLAY||c&&c.type==="operatorname"&&c.alwaysHandleSupSub&&(e.style===kt.DISPLAY||c.limits)?o="munderover":o="msubsup"}else{var l=n.base;l&&l.type==="op"&&l.limits&&(e.style===kt.DISPLAY||l.alwaysHandleSupSub)||l&&l.type==="operatorname"&&l.alwaysHandleSupSub&&(l.limits||e.style===kt.DISPLAY)?o="munder":o="msub"}else{var a=n.base;a&&a.type==="op"&&a.limits&&(e.style===kt.DISPLAY||a.alwaysHandleSupSub)||a&&a.type==="operatorname"&&a.alwaysHandleSupSub&&(a.limits||e.style===kt.DISPLAY)?o="mover":o="msup"}return new Re(o,i)}});ql({type:"atom",htmlBuilder(n,e){return xb(n.text,n.mode,e,["m"+n.family])},mathmlBuilder(n,e){var t=new Re("mo",[ni(n.text,n.mode)]);if(n.family==="bin"){var s=yb(n,e);s==="bold-italic"&&t.setAttribute("mathvariant",s)}else n.family==="punct"?t.setAttribute("separator","true"):(n.family==="open"||n.family==="close")&&t.setAttribute("stretchy","false");return t}});var iR={mi:"italic",mn:"normal",mtext:"normal"};ql({type:"mathord",htmlBuilder(n,e){return hg(n,e,"mathord")},mathmlBuilder(n,e){var t=new Re("mi",[ni(n.text,n.mode,e)]),s=yb(n,e)||"italic";return s!==iR[t.type]&&t.setAttribute("mathvariant",s),t}});ql({type:"textord",htmlBuilder(n,e){return hg(n,e,"textord")},mathmlBuilder(n,e){var t=ni(n.text,n.mode,e),s=yb(n,e)||"normal",r;return n.mode==="text"?r=new Re("mtext",[t]):/[0-9]/.test(n.text)?r=new Re("mn",[t]):n.text==="\\prime"?r=new Re("mo",[t]):r=new Re("mi",[t]),s!==iR[r.type]&&r.setAttribute("mathvariant",s),r}});var z1={"\\nobreak":"nobreak","\\allowbreak":"allowbreak"},B1={" ":{},"\\ ":{},"~":{className:"nobreak"},"\\space":{},"\\nobreakspace":{className:"nobreak"}};ql({type:"spacing",htmlBuilder(n,e){if(B1.hasOwnProperty(n.text)){var t=B1[n.text].className||"";if(n.mode==="text"){var s=hg(n,e,"textord");return s.classes.push(t),s}else return Ee(["mspace",t],[xb(n.text,n.mode,e)],e)}else{if(z1.hasOwnProperty(n.text))return Ee(["mspace",z1[n.text]],[],e);throw new Ae('Unknown type of space "'+n.text+'"')}},mathmlBuilder(n,e){var t;if(B1.hasOwnProperty(n.text))t=new Re("mtext",[new ts(" ")]);else{if(z1.hasOwnProperty(n.text))return new Re("mspace");throw new Ae('Unknown type of space "'+n.text+'"')}return t}});var PS=()=>{var n=new Re("mtd",[]);return n.setAttribute("width","50%"),n};ql({type:"tag",mathmlBuilder(n,e){var t=new Re("mtable",[new Re("mtr",[PS(),new Re("mtd",[va(n.body,e)]),PS(),new Re("mtd",[va(n.tag,e)])])]);return t.setAttribute("width","100%"),t}});var LS={"\\text":void 0,"\\textrm":"textrm","\\textsf":"textsf","\\texttt":"texttt","\\textnormal":"textrm"},FS={"\\textbf":"textbf","\\textmd":"textmd"},n1e={"\\textit":"textit","\\textup":"textup"},OS=(n,e)=>{var t=n.font;if(t){if(LS[t])return e.withTextFontFamily(LS[t]);if(FS[t])return e.withTextFontWeight(FS[t]);if(t==="\\emph")return e.fontShape==="textit"?e.withTextFontShape("textup"):e.withTextFontShape("textit")}else return e;return e.withTextFontShape(n1e[t])};Ye({type:"text",names:["\\text","\\textrm","\\textsf","\\texttt","\\textnormal","\\textbf","\\textmd","\\textit","\\textup","\\emph"],props:{numArgs:1,argTypes:["text"],allowedInArgument:!0,allowedInText:!0},handler(n,e){var{parser:t,funcName:s}=n,r=e[0];return{type:"text",mode:t.mode,body:es(r),font:s}},htmlBuilder(n,e){var t=OS(n,e),s=ms(n.body,t,!0);return Ee(["mord","text"],s,t)},mathmlBuilder(n,e){var t=OS(n,e);return va(n.body,t)}});Ye({type:"underline",names:["\\underline"],props:{numArgs:1,allowedInText:!0},handler(n,e){var{parser:t}=n;return{type:"underline",mode:t.mode,body:e[0]}},htmlBuilder(n,e){var t=tn(n.body,e),s=qc("underline-line",e),r=e.fontMetrics().defaultRuleThickness,i=Qt({positionType:"top",positionData:t.height,children:[{type:"kern",size:r},{type:"elem",elem:s},{type:"kern",size:3*r},{type:"elem",elem:t}]});return Ee(["mord","underline"],[i],e)},mathmlBuilder(n,e){var t=new Re("mo",[new ts("‾")]);t.setAttribute("stretchy","true");var s=new Re("munder",[mn(n.body,e),t]);return s.setAttribute("accentunder","true"),s}});Ye({type:"vcenter",names:["\\vcenter"],props:{numArgs:1,argTypes:["original"],allowedInText:!1},handler(n,e){var{parser:t}=n;return{type:"vcenter",mode:t.mode,body:e[0]}},htmlBuilder(n,e){var t=tn(n.body,e),s=e.fontMetrics().axisHeight,r=.5*(t.height-s-(t.depth+s));return Qt({positionType:"shift",positionData:r,children:[{type:"elem",elem:t}]})},mathmlBuilder(n,e){var t=new Re("mpadded",[mn(n.body,e)],["vcenter"]);return new Re("mrow",[t])}});Ye({type:"verb",names:["\\verb"],props:{numArgs:0,allowedInText:!0},handler(n,e,t){throw new Ae("\\verb ended by end of line instead of matching delimiter")},htmlBuilder(n,e){for(var t=zS(n),s=[],r=e.havingStyle(e.style.text()),i=0;in.body.replace(/ /g,n.star?"␣":" "),Qo=IA,oR=`[ \r + ]`,s1e="\\\\[a-zA-Z@]+",r1e="\\\\[^\uD800-\uDFFF]",i1e="("+s1e+")"+oR+"*",o1e=`\\\\( +|[ \r ]+ +?)[ \r ]*`,e2="[̀-ͯ]",a1e=new RegExp(e2+"+$"),l1e="("+oR+"+)|"+(o1e+"|")+"([!-\\[\\]-‧‪-퟿豈-￿]"+(e2+"*")+"|[\uD800-\uDBFF][\uDC00-\uDFFF]"+(e2+"*")+"|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5"+("|"+i1e)+("|"+r1e+")");class BS{constructor(e,t){this.input=e,this.settings=t,this.tokenRegex=new RegExp(l1e,"g"),this.catcodes={"%":14,"~":13}}setCatcode(e,t){this.catcodes[e]=t}lex(){var e=this.input,t=this.tokenRegex.lastIndex;if(t===e.length)return new Rr("EOF",new hr(this,t,t));var s=this.tokenRegex.exec(e);if(s===null||s.index!==t)throw new Ae("Unexpected character: '"+e[t]+"'",new Rr(e[t],new hr(this,t,t+1)));var r=s[6]||s[3]||(s[2]?"\\ ":" ");if(this.catcodes[r]===14){var i=e.indexOf(` +`,this.tokenRegex.lastIndex);return i===-1?(this.tokenRegex.lastIndex=e.length,this.settings.reportNonstrict("commentAtEnd","% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)")):this.tokenRegex.lastIndex=i+1,this.lex()}return new Rr(r,new hr(this,t,this.tokenRegex.lastIndex))}}class c1e{constructor(e,t){e===void 0&&(e={}),t===void 0&&(t={}),this.current=t,this.builtins=e,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(this.undefStack.length===0)throw new Ae("Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug");var e=this.undefStack.pop();for(var t in e)e.hasOwnProperty(t)&&(e[t]==null?delete this.current[t]:this.current[t]=e[t])}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(e){return this.current.hasOwnProperty(e)||this.builtins.hasOwnProperty(e)}get(e){return this.current.hasOwnProperty(e)?this.current[e]:this.builtins[e]}set(e,t,s){if(s===void 0&&(s=!1),s){for(var r=0;r0&&(this.undefStack[this.undefStack.length-1][e]=t)}else{var i=this.undefStack[this.undefStack.length-1];i&&!i.hasOwnProperty(e)&&(i[e]=this.current[e])}t==null?delete this.current[e]:this.current[e]=t}}var u1e=jA;D("\\noexpand",function(n){var e=n.popToken();return n.isExpandable(e.text)&&(e.noexpand=!0,e.treatAsRelax=!0),{tokens:[e],numArgs:0}});D("\\expandafter",function(n){var e=n.popToken();return n.expandOnce(!0),{tokens:[e],numArgs:0}});D("\\@firstoftwo",function(n){var e=n.consumeArgs(2);return{tokens:e[0],numArgs:0}});D("\\@secondoftwo",function(n){var e=n.consumeArgs(2);return{tokens:e[1],numArgs:0}});D("\\@ifnextchar",function(n){var e=n.consumeArgs(3);n.consumeSpaces();var t=n.future();return e[0].length===1&&e[0][0].text===t.text?{tokens:e[1],numArgs:0}:{tokens:e[2],numArgs:0}});D("\\@ifstar","\\@ifnextchar *{\\@firstoftwo{#1}}");D("\\TextOrMath",function(n){var e=n.consumeArgs(2);return n.mode==="text"?{tokens:e[0],numArgs:0}:{tokens:e[1],numArgs:0}});var US={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};D("\\char",function(n){var e=n.popToken(),t,s=0;if(e.text==="'")t=8,e=n.popToken();else if(e.text==='"')t=16,e=n.popToken();else if(e.text==="`")if(e=n.popToken(),e.text[0]==="\\")s=e.text.charCodeAt(1);else{if(e.text==="EOF")throw new Ae("\\char` missing argument");s=e.text.charCodeAt(0)}else t=10;if(t){if(s=US[e.text],s==null||s>=t)throw new Ae("Invalid base-"+t+" digit "+e.text);for(var r;(r=US[n.future().text])!=null&&r{var r=n.consumeArg().tokens;if(r.length!==1)throw new Ae("\\newcommand's first argument must be a macro name");var i=r[0].text,o=n.isDefined(i);if(o&&!e)throw new Ae("\\newcommand{"+i+"} attempting to redefine "+(i+"; use \\renewcommand"));if(!o&&!t)throw new Ae("\\renewcommand{"+i+"} when command "+i+" does not yet exist; use \\newcommand");var a=0;if(r=n.consumeArg().tokens,r.length===1&&r[0].text==="["){for(var l="",c=n.expandNextToken();c.text!=="]"&&c.text!=="EOF";)l+=c.text,c=n.expandNextToken();if(!l.match(/^\s*[0-9]+\s*$/))throw new Ae("Invalid number of arguments: "+l);a=parseInt(l),r=n.consumeArg().tokens}return o&&s||n.macros.set(i,{tokens:r,numArgs:a}),""};D("\\newcommand",n=>Tb(n,!1,!0,!1));D("\\renewcommand",n=>Tb(n,!0,!1,!1));D("\\providecommand",n=>Tb(n,!0,!0,!0));D("\\message",n=>{var e=n.consumeArgs(1)[0];return console.log(e.reverse().map(t=>t.text).join("")),""});D("\\errmessage",n=>{var e=n.consumeArgs(1)[0];return console.error(e.reverse().map(t=>t.text).join("")),""});D("\\show",n=>{var e=n.popToken(),t=e.text;return console.log(e,n.macros.get(t),Qo[t],Rn.math[t],Rn.text[t]),""});D("\\bgroup","{");D("\\egroup","}");D("~","\\nobreakspace");D("\\lq","`");D("\\rq","'");D("\\aa","\\r a");D("\\AA","\\r A");D("\\textcopyright","\\html@mathml{\\textcircled{c}}{\\char`©}");D("\\copyright","\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}");D("\\textregistered","\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`®}");D("ℬ","\\mathscr{B}");D("ℰ","\\mathscr{E}");D("ℱ","\\mathscr{F}");D("ℋ","\\mathscr{H}");D("ℐ","\\mathscr{I}");D("ℒ","\\mathscr{L}");D("ℳ","\\mathscr{M}");D("ℛ","\\mathscr{R}");D("ℭ","\\mathfrak{C}");D("ℌ","\\mathfrak{H}");D("ℨ","\\mathfrak{Z}");D("\\Bbbk","\\Bbb{k}");D("\\llap","\\mathllap{\\textrm{#1}}");D("\\rlap","\\mathrlap{\\textrm{#1}}");D("\\clap","\\mathclap{\\textrm{#1}}");D("\\mathstrut","\\vphantom{(}");D("\\underbar","\\underline{\\text{#1}}");D("\\not",'\\html@mathml{\\mathrel{\\mathrlap\\@not}\\nobreak}{\\char"338}');D("\\neq","\\html@mathml{\\mathrel{\\not=}}{\\mathrel{\\char`≠}}");D("\\ne","\\neq");D("≠","\\neq");D("\\notin","\\html@mathml{\\mathrel{{\\in}\\mathllap{/\\mskip1mu}}}{\\mathrel{\\char`∉}}");D("∉","\\notin");D("≘","\\html@mathml{\\mathrel{=\\kern{-1em}\\raisebox{0.4em}{$\\scriptsize\\frown$}}}{\\mathrel{\\char`≘}}");D("≙","\\html@mathml{\\stackrel{\\tiny\\wedge}{=}}{\\mathrel{\\char`≘}}");D("≚","\\html@mathml{\\stackrel{\\tiny\\vee}{=}}{\\mathrel{\\char`≚}}");D("≛","\\html@mathml{\\stackrel{\\scriptsize\\star}{=}}{\\mathrel{\\char`≛}}");D("≝","\\html@mathml{\\stackrel{\\tiny\\mathrm{def}}{=}}{\\mathrel{\\char`≝}}");D("≞","\\html@mathml{\\stackrel{\\tiny\\mathrm{m}}{=}}{\\mathrel{\\char`≞}}");D("≟","\\html@mathml{\\stackrel{\\tiny?}{=}}{\\mathrel{\\char`≟}}");D("⟂","\\perp");D("‼","\\mathclose{!\\mkern-0.8mu!}");D("∌","\\notni");D("⌜","\\ulcorner");D("⌝","\\urcorner");D("⌞","\\llcorner");D("⌟","\\lrcorner");D("©","\\copyright");D("®","\\textregistered");D("\\ulcorner",'\\html@mathml{\\@ulcorner}{\\mathop{\\char"231c}}');D("\\urcorner",'\\html@mathml{\\@urcorner}{\\mathop{\\char"231d}}');D("\\llcorner",'\\html@mathml{\\@llcorner}{\\mathop{\\char"231e}}');D("\\lrcorner",'\\html@mathml{\\@lrcorner}{\\mathop{\\char"231f}}');D("\\vdots","{\\varvdots\\rule{0pt}{15pt}}");D("⋮","\\vdots");D("\\varGamma","\\mathit{\\Gamma}");D("\\varDelta","\\mathit{\\Delta}");D("\\varTheta","\\mathit{\\Theta}");D("\\varLambda","\\mathit{\\Lambda}");D("\\varXi","\\mathit{\\Xi}");D("\\varPi","\\mathit{\\Pi}");D("\\varSigma","\\mathit{\\Sigma}");D("\\varUpsilon","\\mathit{\\Upsilon}");D("\\varPhi","\\mathit{\\Phi}");D("\\varPsi","\\mathit{\\Psi}");D("\\varOmega","\\mathit{\\Omega}");D("\\substack","\\begin{subarray}{c}#1\\end{subarray}");D("\\colon","\\nobreak\\mskip2mu\\mathpunct{}\\mathchoice{\\mkern-3mu}{\\mkern-3mu}{}{}{:}\\mskip6mu\\relax");D("\\boxed","\\fbox{$\\displaystyle{#1}$}");D("\\iff","\\DOTSB\\;\\Longleftrightarrow\\;");D("\\implies","\\DOTSB\\;\\Longrightarrow\\;");D("\\impliedby","\\DOTSB\\;\\Longleftarrow\\;");D("\\dddot","{\\overset{\\raisebox{-0.1ex}{\\normalsize ...}}{#1}}");D("\\ddddot","{\\overset{\\raisebox{-0.1ex}{\\normalsize ....}}{#1}}");var VS={",":"\\dotsc","\\not":"\\dotsb","+":"\\dotsb","=":"\\dotsb","<":"\\dotsb",">":"\\dotsb","-":"\\dotsb","*":"\\dotsb",":":"\\dotsb","\\DOTSB":"\\dotsb","\\coprod":"\\dotsb","\\bigvee":"\\dotsb","\\bigwedge":"\\dotsb","\\biguplus":"\\dotsb","\\bigcap":"\\dotsb","\\bigcup":"\\dotsb","\\prod":"\\dotsb","\\sum":"\\dotsb","\\bigotimes":"\\dotsb","\\bigoplus":"\\dotsb","\\bigodot":"\\dotsb","\\bigsqcup":"\\dotsb","\\And":"\\dotsb","\\longrightarrow":"\\dotsb","\\Longrightarrow":"\\dotsb","\\longleftarrow":"\\dotsb","\\Longleftarrow":"\\dotsb","\\longleftrightarrow":"\\dotsb","\\Longleftrightarrow":"\\dotsb","\\mapsto":"\\dotsb","\\longmapsto":"\\dotsb","\\hookrightarrow":"\\dotsb","\\doteq":"\\dotsb","\\mathbin":"\\dotsb","\\mathrel":"\\dotsb","\\relbar":"\\dotsb","\\Relbar":"\\dotsb","\\xrightarrow":"\\dotsb","\\xleftarrow":"\\dotsb","\\DOTSI":"\\dotsi","\\int":"\\dotsi","\\oint":"\\dotsi","\\iint":"\\dotsi","\\iiint":"\\dotsi","\\iiiint":"\\dotsi","\\idotsint":"\\dotsi","\\DOTSX":"\\dotsx"},h1e=new Set(["bin","rel"]);D("\\dots",function(n){var e="\\dotso",t=n.expandAfterFuture().text;return t in VS?e=VS[t]:(t.slice(0,4)==="\\not"||t in Rn.math&&h1e.has(Rn.math[t].group))&&(e="\\dotsb"),e});var Ib={")":!0,"]":!0,"\\rbrack":!0,"\\}":!0,"\\rbrace":!0,"\\rangle":!0,"\\rceil":!0,"\\rfloor":!0,"\\rgroup":!0,"\\rmoustache":!0,"\\right":!0,"\\bigr":!0,"\\biggr":!0,"\\Bigr":!0,"\\Biggr":!0,$:!0,";":!0,".":!0,",":!0};D("\\dotso",function(n){var e=n.future().text;return e in Ib?"\\ldots\\,":"\\ldots"});D("\\dotsc",function(n){var e=n.future().text;return e in Ib&&e!==","?"\\ldots\\,":"\\ldots"});D("\\cdots",function(n){var e=n.future().text;return e in Ib?"\\@cdots\\,":"\\@cdots"});D("\\dotsb","\\cdots");D("\\dotsm","\\cdots");D("\\dotsi","\\!\\cdots");D("\\dotsx","\\ldots\\,");D("\\DOTSI","\\relax");D("\\DOTSB","\\relax");D("\\DOTSX","\\relax");D("\\tmspace","\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax");D("\\,","\\tmspace+{3mu}{.1667em}");D("\\thinspace","\\,");D("\\>","\\mskip{4mu}");D("\\:","\\tmspace+{4mu}{.2222em}");D("\\medspace","\\:");D("\\;","\\tmspace+{5mu}{.2777em}");D("\\thickspace","\\;");D("\\!","\\tmspace-{3mu}{.1667em}");D("\\negthinspace","\\!");D("\\negmedspace","\\tmspace-{4mu}{.2222em}");D("\\negthickspace","\\tmspace-{5mu}{.277em}");D("\\enspace","\\kern.5em ");D("\\enskip","\\hskip.5em\\relax");D("\\quad","\\hskip1em\\relax");D("\\qquad","\\hskip2em\\relax");D("\\tag","\\@ifstar\\tag@literal\\tag@paren");D("\\tag@paren","\\tag@literal{({#1})}");D("\\tag@literal",n=>{if(n.macros.get("\\df@tag"))throw new Ae("Multiple \\tag");return"\\gdef\\df@tag{\\text{#1}}"});D("\\bmod","\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}\\mathbin{\\rm mod}\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}");D("\\pod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)");D("\\pmod","\\pod{{\\rm mod}\\mkern6mu#1}");D("\\mod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}{\\rm mod}\\,\\,#1");D("\\newline","\\\\\\relax");D("\\TeX","\\textrm{\\html@mathml{T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX}{TeX}}");var aR=Ne(Wi["Main-Regular"][84][1]-.7*Wi["Main-Regular"][65][1]);D("\\LaTeX","\\textrm{\\html@mathml{"+("L\\kern-.36em\\raisebox{"+aR+"}{\\scriptstyle A}")+"\\kern-.15em\\TeX}{LaTeX}}");D("\\KaTeX","\\textrm{\\html@mathml{"+("K\\kern-.17em\\raisebox{"+aR+"}{\\scriptstyle A}")+"\\kern-.15em\\TeX}{KaTeX}}");D("\\hspace","\\@ifstar\\@hspacer\\@hspace");D("\\@hspace","\\hskip #1\\relax");D("\\@hspacer","\\rule{0pt}{0pt}\\hskip #1\\relax");D("\\ordinarycolon",":");D("\\vcentcolon","\\mathrel{\\mathop\\ordinarycolon}");D("\\dblcolon",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}{\\mathop{\\char"2237}}');D("\\coloneqq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2254}}');D("\\Coloneqq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2237\\char"3d}}');D("\\coloneq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"3a\\char"2212}}');D("\\Coloneq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"2237\\char"2212}}');D("\\eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2255}}');D("\\Eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"3d\\char"2237}}');D("\\eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2239}}');D("\\Eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"2212\\char"2237}}');D("\\colonapprox",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"3a\\char"2248}}');D("\\Colonapprox",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"2237\\char"2248}}');D("\\colonsim",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"3a\\char"223c}}');D("\\Colonsim",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"2237\\char"223c}}');D("∷","\\dblcolon");D("∹","\\eqcolon");D("≔","\\coloneqq");D("≕","\\eqqcolon");D("⩴","\\Coloneqq");D("\\ratio","\\vcentcolon");D("\\coloncolon","\\dblcolon");D("\\colonequals","\\coloneqq");D("\\coloncolonequals","\\Coloneqq");D("\\equalscolon","\\eqqcolon");D("\\equalscoloncolon","\\Eqqcolon");D("\\colonminus","\\coloneq");D("\\coloncolonminus","\\Coloneq");D("\\minuscolon","\\eqcolon");D("\\minuscoloncolon","\\Eqcolon");D("\\coloncolonapprox","\\Colonapprox");D("\\coloncolonsim","\\Colonsim");D("\\simcolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}");D("\\simcoloncolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}");D("\\approxcolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}");D("\\approxcoloncolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}");D("\\notni","\\html@mathml{\\not\\ni}{\\mathrel{\\char`∌}}");D("\\limsup","\\DOTSB\\operatorname*{lim\\,sup}");D("\\liminf","\\DOTSB\\operatorname*{lim\\,inf}");D("\\injlim","\\DOTSB\\operatorname*{inj\\,lim}");D("\\projlim","\\DOTSB\\operatorname*{proj\\,lim}");D("\\varlimsup","\\DOTSB\\operatorname*{\\overline{lim}}");D("\\varliminf","\\DOTSB\\operatorname*{\\underline{lim}}");D("\\varinjlim","\\DOTSB\\operatorname*{\\underrightarrow{lim}}");D("\\varprojlim","\\DOTSB\\operatorname*{\\underleftarrow{lim}}");D("\\gvertneqq","\\html@mathml{\\@gvertneqq}{≩}");D("\\lvertneqq","\\html@mathml{\\@lvertneqq}{≨}");D("\\ngeqq","\\html@mathml{\\@ngeqq}{≱}");D("\\ngeqslant","\\html@mathml{\\@ngeqslant}{≱}");D("\\nleqq","\\html@mathml{\\@nleqq}{≰}");D("\\nleqslant","\\html@mathml{\\@nleqslant}{≰}");D("\\nshortmid","\\html@mathml{\\@nshortmid}{∤}");D("\\nshortparallel","\\html@mathml{\\@nshortparallel}{∦}");D("\\nsubseteqq","\\html@mathml{\\@nsubseteqq}{⊈}");D("\\nsupseteqq","\\html@mathml{\\@nsupseteqq}{⊉}");D("\\varsubsetneq","\\html@mathml{\\@varsubsetneq}{⊊}");D("\\varsubsetneqq","\\html@mathml{\\@varsubsetneqq}{⫋}");D("\\varsupsetneq","\\html@mathml{\\@varsupsetneq}{⊋}");D("\\varsupsetneqq","\\html@mathml{\\@varsupsetneqq}{⫌}");D("\\imath","\\html@mathml{\\@imath}{ı}");D("\\jmath","\\html@mathml{\\@jmath}{ȷ}");D("\\llbracket","\\html@mathml{\\mathopen{[\\mkern-3.2mu[}}{\\mathopen{\\char`⟦}}");D("\\rrbracket","\\html@mathml{\\mathclose{]\\mkern-3.2mu]}}{\\mathclose{\\char`⟧}}");D("⟦","\\llbracket");D("⟧","\\rrbracket");D("\\lBrace","\\html@mathml{\\mathopen{\\{\\mkern-3.2mu[}}{\\mathopen{\\char`⦃}}");D("\\rBrace","\\html@mathml{\\mathclose{]\\mkern-3.2mu\\}}}{\\mathclose{\\char`⦄}}");D("⦃","\\lBrace");D("⦄","\\rBrace");D("\\minuso","\\mathbin{\\html@mathml{{\\mathrlap{\\mathchoice{\\kern{0.145em}}{\\kern{0.145em}}{\\kern{0.1015em}}{\\kern{0.0725em}}\\circ}{-}}}{\\char`⦵}}");D("⦵","\\minuso");D("\\darr","\\downarrow");D("\\dArr","\\Downarrow");D("\\Darr","\\Downarrow");D("\\lang","\\langle");D("\\rang","\\rangle");D("\\uarr","\\uparrow");D("\\uArr","\\Uparrow");D("\\Uarr","\\Uparrow");D("\\N","\\mathbb{N}");D("\\R","\\mathbb{R}");D("\\Z","\\mathbb{Z}");D("\\alef","\\aleph");D("\\alefsym","\\aleph");D("\\Alpha","\\mathrm{A}");D("\\Beta","\\mathrm{B}");D("\\bull","\\bullet");D("\\Chi","\\mathrm{X}");D("\\clubs","\\clubsuit");D("\\cnums","\\mathbb{C}");D("\\Complex","\\mathbb{C}");D("\\Dagger","\\ddagger");D("\\diamonds","\\diamondsuit");D("\\empty","\\emptyset");D("\\Epsilon","\\mathrm{E}");D("\\Eta","\\mathrm{H}");D("\\exist","\\exists");D("\\harr","\\leftrightarrow");D("\\hArr","\\Leftrightarrow");D("\\Harr","\\Leftrightarrow");D("\\hearts","\\heartsuit");D("\\image","\\Im");D("\\infin","\\infty");D("\\Iota","\\mathrm{I}");D("\\isin","\\in");D("\\Kappa","\\mathrm{K}");D("\\larr","\\leftarrow");D("\\lArr","\\Leftarrow");D("\\Larr","\\Leftarrow");D("\\lrarr","\\leftrightarrow");D("\\lrArr","\\Leftrightarrow");D("\\Lrarr","\\Leftrightarrow");D("\\Mu","\\mathrm{M}");D("\\natnums","\\mathbb{N}");D("\\Nu","\\mathrm{N}");D("\\Omicron","\\mathrm{O}");D("\\plusmn","\\pm");D("\\rarr","\\rightarrow");D("\\rArr","\\Rightarrow");D("\\Rarr","\\Rightarrow");D("\\real","\\Re");D("\\reals","\\mathbb{R}");D("\\Reals","\\mathbb{R}");D("\\Rho","\\mathrm{P}");D("\\sdot","\\cdot");D("\\sect","\\S");D("\\spades","\\spadesuit");D("\\sub","\\subset");D("\\sube","\\subseteq");D("\\supe","\\supseteq");D("\\Tau","\\mathrm{T}");D("\\thetasym","\\vartheta");D("\\weierp","\\wp");D("\\Zeta","\\mathrm{Z}");D("\\argmin","\\DOTSB\\operatorname*{arg\\,min}");D("\\argmax","\\DOTSB\\operatorname*{arg\\,max}");D("\\plim","\\DOTSB\\mathop{\\operatorname{plim}}\\limits");D("\\bra","\\mathinner{\\langle{#1}|}");D("\\ket","\\mathinner{|{#1}\\rangle}");D("\\braket","\\mathinner{\\langle{#1}\\rangle}");D("\\Bra","\\left\\langle#1\\right|");D("\\Ket","\\left|#1\\right\\rangle");var lR=n=>e=>{var t=e.consumeArg().tokens,s=e.consumeArg().tokens,r=e.consumeArg().tokens,i=e.consumeArg().tokens,o=e.macros.get("|"),a=e.macros.get("\\|");e.macros.beginGroup();var l=h=>d=>{n&&(d.macros.set("|",o),r.length&&d.macros.set("\\|",a));var p=h;if(!h&&r.length){var f=d.future();f.text==="|"&&(d.popToken(),p=!0)}return{tokens:p?r:s,numArgs:0}};e.macros.set("|",l(!1)),r.length&&e.macros.set("\\|",l(!0));var c=e.consumeArg().tokens,u=e.expandTokens([...i,...c,...t]);return e.macros.endGroup(),{tokens:u.reverse(),numArgs:0}};D("\\bra@ket",lR(!1));D("\\bra@set",lR(!0));D("\\Braket","\\bra@ket{\\left\\langle}{\\,\\middle\\vert\\,}{\\,\\middle\\vert\\,}{\\right\\rangle}");D("\\Set","\\bra@set{\\left\\{\\:}{\\;\\middle\\vert\\;}{\\;\\middle\\Vert\\;}{\\:\\right\\}}");D("\\set","\\bra@set{\\{\\,}{\\mid}{}{\\,\\}}");D("\\angln","{\\angl n}");D("\\blue","\\textcolor{##6495ed}{#1}");D("\\orange","\\textcolor{##ffa500}{#1}");D("\\pink","\\textcolor{##ff00af}{#1}");D("\\red","\\textcolor{##df0030}{#1}");D("\\green","\\textcolor{##28ae7b}{#1}");D("\\gray","\\textcolor{gray}{#1}");D("\\purple","\\textcolor{##9d38bd}{#1}");D("\\blueA","\\textcolor{##ccfaff}{#1}");D("\\blueB","\\textcolor{##80f6ff}{#1}");D("\\blueC","\\textcolor{##63d9ea}{#1}");D("\\blueD","\\textcolor{##11accd}{#1}");D("\\blueE","\\textcolor{##0c7f99}{#1}");D("\\tealA","\\textcolor{##94fff5}{#1}");D("\\tealB","\\textcolor{##26edd5}{#1}");D("\\tealC","\\textcolor{##01d1c1}{#1}");D("\\tealD","\\textcolor{##01a995}{#1}");D("\\tealE","\\textcolor{##208170}{#1}");D("\\greenA","\\textcolor{##b6ffb0}{#1}");D("\\greenB","\\textcolor{##8af281}{#1}");D("\\greenC","\\textcolor{##74cf70}{#1}");D("\\greenD","\\textcolor{##1fab54}{#1}");D("\\greenE","\\textcolor{##0d923f}{#1}");D("\\goldA","\\textcolor{##ffd0a9}{#1}");D("\\goldB","\\textcolor{##ffbb71}{#1}");D("\\goldC","\\textcolor{##ff9c39}{#1}");D("\\goldD","\\textcolor{##e07d10}{#1}");D("\\goldE","\\textcolor{##a75a05}{#1}");D("\\redA","\\textcolor{##fca9a9}{#1}");D("\\redB","\\textcolor{##ff8482}{#1}");D("\\redC","\\textcolor{##f9685d}{#1}");D("\\redD","\\textcolor{##e84d39}{#1}");D("\\redE","\\textcolor{##bc2612}{#1}");D("\\maroonA","\\textcolor{##ffbde0}{#1}");D("\\maroonB","\\textcolor{##ff92c6}{#1}");D("\\maroonC","\\textcolor{##ed5fa6}{#1}");D("\\maroonD","\\textcolor{##ca337c}{#1}");D("\\maroonE","\\textcolor{##9e034e}{#1}");D("\\purpleA","\\textcolor{##ddd7ff}{#1}");D("\\purpleB","\\textcolor{##c6b9fc}{#1}");D("\\purpleC","\\textcolor{##aa87ff}{#1}");D("\\purpleD","\\textcolor{##7854ab}{#1}");D("\\purpleE","\\textcolor{##543b78}{#1}");D("\\mintA","\\textcolor{##f5f9e8}{#1}");D("\\mintB","\\textcolor{##edf2df}{#1}");D("\\mintC","\\textcolor{##e0e5cc}{#1}");D("\\grayA","\\textcolor{##f6f7f7}{#1}");D("\\grayB","\\textcolor{##f0f1f2}{#1}");D("\\grayC","\\textcolor{##e3e5e6}{#1}");D("\\grayD","\\textcolor{##d6d8da}{#1}");D("\\grayE","\\textcolor{##babec2}{#1}");D("\\grayF","\\textcolor{##888d93}{#1}");D("\\grayG","\\textcolor{##626569}{#1}");D("\\grayH","\\textcolor{##3b3e40}{#1}");D("\\grayI","\\textcolor{##21242c}{#1}");D("\\kaBlue","\\textcolor{##314453}{#1}");D("\\kaGreen","\\textcolor{##71B307}{#1}");var cR={"^":!0,_:!0,"\\limits":!0,"\\nolimits":!0};class d1e{constructor(e,t,s){this.settings=t,this.expansionCount=0,this.feed(e),this.macros=new c1e(u1e,t.macros),this.mode=s,this.stack=[]}feed(e){this.lexer=new BS(e,this.settings)}switchMode(e){this.mode=e}beginGroup(){this.macros.beginGroup()}endGroup(){this.macros.endGroup()}endGroups(){this.macros.endGroups()}future(){return this.stack.length===0&&this.pushToken(this.lexer.lex()),this.stack[this.stack.length-1]}popToken(){return this.future(),this.stack.pop()}pushToken(e){this.stack.push(e)}pushTokens(e){this.stack.push(...e)}scanArgument(e){var t,s,r;if(e){if(this.consumeSpaces(),this.future().text!=="[")return null;t=this.popToken(),{tokens:r,end:s}=this.consumeArg(["]"])}else({tokens:r,start:t,end:s}=this.consumeArg());return this.pushToken(new Rr("EOF",s.loc)),this.pushTokens(r),new Rr("",hr.range(t,s))}consumeSpaces(){for(;;){var e=this.future();if(e.text===" ")this.stack.pop();else break}}consumeArg(e){var t=[],s=e&&e.length>0;s||this.consumeSpaces();var r=this.future(),i,o=0,a=0;do{if(i=this.popToken(),t.push(i),i.text==="{")++o;else if(i.text==="}"){if(--o,o===-1)throw new Ae("Extra }",i)}else if(i.text==="EOF")throw new Ae("Unexpected end of input in a macro argument, expected '"+(e&&s?e[a]:"}")+"'",i);if(e&&s)if((o===0||o===1&&e[a]==="{")&&i.text===e[a]){if(++a,a===e.length){t.splice(-a,a);break}}else a=0}while(o!==0||s);return r.text==="{"&&t[t.length-1].text==="}"&&(t.pop(),t.shift()),t.reverse(),{tokens:t,start:r,end:i}}consumeArgs(e,t){if(t){if(t.length!==e+1)throw new Ae("The length of delimiters doesn't match the number of args!");for(var s=t[0],r=0;rthis.settings.maxExpand)throw new Ae("Too many expansions: infinite loop or need to increase maxExpand setting")}expandOnce(e){var t=this.popToken(),s=t.text,r=t.noexpand?null:this._getExpansion(s);if(r==null||e&&r.unexpandable){if(e&&r==null&&s[0]==="\\"&&!this.isDefined(s))throw new Ae("Undefined control sequence: "+s);return this.pushToken(t),!1}this.countExpansion(1);var i=r.tokens,o=this.consumeArgs(r.numArgs,r.delimiters);if(r.numArgs){i=i.slice();for(var a=i.length-1;a>=0;--a){var l=i[a];if(l.text==="#"){if(a===0)throw new Ae("Incomplete placeholder at end of macro body",l);if(l=i[--a],l.text==="#")i.splice(a+1,1);else if(/^[1-9]$/.test(l.text))i.splice(a,2,...o[+l.text-1]);else throw new Ae("Not a valid argument number",l)}}}return this.pushTokens(i),i.length}expandAfterFuture(){return this.expandOnce(),this.future()}expandNextToken(){for(;;)if(this.expandOnce()===!1){var e=this.stack.pop();return e.treatAsRelax&&(e.text="\\relax"),e}}expandMacro(e){return this.macros.has(e)?this.expandTokens([new Rr(e)]):void 0}expandTokens(e){var t=[],s=this.stack.length;for(this.pushTokens(e);this.stack.length>s;)if(this.expandOnce(!0)===!1){var r=this.stack.pop();r.treatAsRelax&&(r.noexpand=!1,r.treatAsRelax=!1),t.push(r)}return this.countExpansion(t.length),t}expandMacroAsText(e){var t=this.expandMacro(e);return t&&t.map(s=>s.text).join("")}_getExpansion(e){var t=this.macros.get(e);if(t==null)return t;if(e.length===1){var s=this.lexer.catcodes[e];if(s!=null&&s!==13)return}var r=typeof t=="function"?t(this):t;if(typeof r=="string"){var i=0;if(r.includes("#"))for(var o=r.replace(/##/g,"");o.includes("#"+(i+1));)++i;for(var a=new BS(r,this.settings),l=[],c=a.lex();c.text!=="EOF";)l.push(c),c=a.lex();l.reverse();var u={tokens:l,numArgs:i};return u}return r}isDefined(e){return this.macros.has(e)||Qo.hasOwnProperty(e)||Rn.math.hasOwnProperty(e)||Rn.text.hasOwnProperty(e)||cR.hasOwnProperty(e)}isExpandable(e){var t=this.macros.get(e);return t!=null?typeof t=="string"||typeof t=="function"||!t.unexpandable:Qo.hasOwnProperty(e)&&!Qo[e].primitive}}var WS=/^[₊₋₌₍₎₀₁₂₃₄₅₆₇₈₉ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᵦᵧᵨᵩᵪ]/,wf=Object.freeze({"₊":"+","₋":"-","₌":"=","₍":"(","₎":")","₀":"0","₁":"1","₂":"2","₃":"3","₄":"4","₅":"5","₆":"6","₇":"7","₈":"8","₉":"9","ₐ":"a","ₑ":"e","ₕ":"h","ᵢ":"i","ⱼ":"j","ₖ":"k","ₗ":"l","ₘ":"m","ₙ":"n","ₒ":"o","ₚ":"p","ᵣ":"r","ₛ":"s","ₜ":"t","ᵤ":"u","ᵥ":"v","ₓ":"x","ᵦ":"β","ᵧ":"γ","ᵨ":"ρ","ᵩ":"ϕ","ᵪ":"χ","⁺":"+","⁻":"-","⁼":"=","⁽":"(","⁾":")","⁰":"0","¹":"1","²":"2","³":"3","⁴":"4","⁵":"5","⁶":"6","⁷":"7","⁸":"8","⁹":"9","ᴬ":"A","ᴮ":"B","ᴰ":"D","ᴱ":"E","ᴳ":"G","ᴴ":"H","ᴵ":"I","ᴶ":"J","ᴷ":"K","ᴸ":"L","ᴹ":"M","ᴺ":"N","ᴼ":"O","ᴾ":"P","ᴿ":"R","ᵀ":"T","ᵁ":"U","ⱽ":"V","ᵂ":"W","ᵃ":"a","ᵇ":"b","ᶜ":"c","ᵈ":"d","ᵉ":"e","ᶠ":"f","ᵍ":"g",ʰ:"h","ⁱ":"i",ʲ:"j","ᵏ":"k",ˡ:"l","ᵐ":"m",ⁿ:"n","ᵒ":"o","ᵖ":"p",ʳ:"r",ˢ:"s","ᵗ":"t","ᵘ":"u","ᵛ":"v",ʷ:"w",ˣ:"x",ʸ:"y","ᶻ":"z","ᵝ":"β","ᵞ":"γ","ᵟ":"δ","ᵠ":"ϕ","ᵡ":"χ","ᶿ":"θ"}),U1={"́":{text:"\\'",math:"\\acute"},"̀":{text:"\\`",math:"\\grave"},"̈":{text:'\\"',math:"\\ddot"},"̃":{text:"\\~",math:"\\tilde"},"̄":{text:"\\=",math:"\\bar"},"̆":{text:"\\u",math:"\\breve"},"̌":{text:"\\v",math:"\\check"},"̂":{text:"\\^",math:"\\hat"},"̇":{text:"\\.",math:"\\dot"},"̊":{text:"\\r",math:"\\mathring"},"̋":{text:"\\H"},"̧":{text:"\\c"}},GS={á:"á",à:"à",ä:"ä",ǟ:"ǟ",ã:"ã",ā:"ā",ă:"ă",ắ:"ắ",ằ:"ằ",ẵ:"ẵ",ǎ:"ǎ",â:"â",ấ:"ấ",ầ:"ầ",ẫ:"ẫ",ȧ:"ȧ",ǡ:"ǡ",å:"å",ǻ:"ǻ",ḃ:"ḃ",ć:"ć",ḉ:"ḉ",č:"č",ĉ:"ĉ",ċ:"ċ",ç:"ç",ď:"ď",ḋ:"ḋ",ḑ:"ḑ",é:"é",è:"è",ë:"ë",ẽ:"ẽ",ē:"ē",ḗ:"ḗ",ḕ:"ḕ",ĕ:"ĕ",ḝ:"ḝ",ě:"ě",ê:"ê",ế:"ế",ề:"ề",ễ:"ễ",ė:"ė",ȩ:"ȩ",ḟ:"ḟ",ǵ:"ǵ",ḡ:"ḡ",ğ:"ğ",ǧ:"ǧ",ĝ:"ĝ",ġ:"ġ",ģ:"ģ",ḧ:"ḧ",ȟ:"ȟ",ĥ:"ĥ",ḣ:"ḣ",ḩ:"ḩ",í:"í",ì:"ì",ï:"ï",ḯ:"ḯ",ĩ:"ĩ",ī:"ī",ĭ:"ĭ",ǐ:"ǐ",î:"î",ǰ:"ǰ",ĵ:"ĵ",ḱ:"ḱ",ǩ:"ǩ",ķ:"ķ",ĺ:"ĺ",ľ:"ľ",ļ:"ļ",ḿ:"ḿ",ṁ:"ṁ",ń:"ń",ǹ:"ǹ",ñ:"ñ",ň:"ň",ṅ:"ṅ",ņ:"ņ",ó:"ó",ò:"ò",ö:"ö",ȫ:"ȫ",õ:"õ",ṍ:"ṍ",ṏ:"ṏ",ȭ:"ȭ",ō:"ō",ṓ:"ṓ",ṑ:"ṑ",ŏ:"ŏ",ǒ:"ǒ",ô:"ô",ố:"ố",ồ:"ồ",ỗ:"ỗ",ȯ:"ȯ",ȱ:"ȱ",ő:"ő",ṕ:"ṕ",ṗ:"ṗ",ŕ:"ŕ",ř:"ř",ṙ:"ṙ",ŗ:"ŗ",ś:"ś",ṥ:"ṥ",š:"š",ṧ:"ṧ",ŝ:"ŝ",ṡ:"ṡ",ş:"ş",ẗ:"ẗ",ť:"ť",ṫ:"ṫ",ţ:"ţ",ú:"ú",ù:"ù",ü:"ü",ǘ:"ǘ",ǜ:"ǜ",ǖ:"ǖ",ǚ:"ǚ",ũ:"ũ",ṹ:"ṹ",ū:"ū",ṻ:"ṻ",ŭ:"ŭ",ǔ:"ǔ",û:"û",ů:"ů",ű:"ű",ṽ:"ṽ",ẃ:"ẃ",ẁ:"ẁ",ẅ:"ẅ",ŵ:"ŵ",ẇ:"ẇ",ẘ:"ẘ",ẍ:"ẍ",ẋ:"ẋ",ý:"ý",ỳ:"ỳ",ÿ:"ÿ",ỹ:"ỹ",ȳ:"ȳ",ŷ:"ŷ",ẏ:"ẏ",ẙ:"ẙ",ź:"ź",ž:"ž",ẑ:"ẑ",ż:"ż",Á:"Á",À:"À",Ä:"Ä",Ǟ:"Ǟ",Ã:"Ã",Ā:"Ā",Ă:"Ă",Ắ:"Ắ",Ằ:"Ằ",Ẵ:"Ẵ",Ǎ:"Ǎ",Â:"Â",Ấ:"Ấ",Ầ:"Ầ",Ẫ:"Ẫ",Ȧ:"Ȧ",Ǡ:"Ǡ",Å:"Å",Ǻ:"Ǻ",Ḃ:"Ḃ",Ć:"Ć",Ḉ:"Ḉ",Č:"Č",Ĉ:"Ĉ",Ċ:"Ċ",Ç:"Ç",Ď:"Ď",Ḋ:"Ḋ",Ḑ:"Ḑ",É:"É",È:"È",Ë:"Ë",Ẽ:"Ẽ",Ē:"Ē",Ḗ:"Ḗ",Ḕ:"Ḕ",Ĕ:"Ĕ",Ḝ:"Ḝ",Ě:"Ě",Ê:"Ê",Ế:"Ế",Ề:"Ề",Ễ:"Ễ",Ė:"Ė",Ȩ:"Ȩ",Ḟ:"Ḟ",Ǵ:"Ǵ",Ḡ:"Ḡ",Ğ:"Ğ",Ǧ:"Ǧ",Ĝ:"Ĝ",Ġ:"Ġ",Ģ:"Ģ",Ḧ:"Ḧ",Ȟ:"Ȟ",Ĥ:"Ĥ",Ḣ:"Ḣ",Ḩ:"Ḩ",Í:"Í",Ì:"Ì",Ï:"Ï",Ḯ:"Ḯ",Ĩ:"Ĩ",Ī:"Ī",Ĭ:"Ĭ",Ǐ:"Ǐ",Î:"Î",İ:"İ",Ĵ:"Ĵ",Ḱ:"Ḱ",Ǩ:"Ǩ",Ķ:"Ķ",Ĺ:"Ĺ",Ľ:"Ľ",Ļ:"Ļ",Ḿ:"Ḿ",Ṁ:"Ṁ",Ń:"Ń",Ǹ:"Ǹ",Ñ:"Ñ",Ň:"Ň",Ṅ:"Ṅ",Ņ:"Ņ",Ó:"Ó",Ò:"Ò",Ö:"Ö",Ȫ:"Ȫ",Õ:"Õ",Ṍ:"Ṍ",Ṏ:"Ṏ",Ȭ:"Ȭ",Ō:"Ō",Ṓ:"Ṓ",Ṑ:"Ṑ",Ŏ:"Ŏ",Ǒ:"Ǒ",Ô:"Ô",Ố:"Ố",Ồ:"Ồ",Ỗ:"Ỗ",Ȯ:"Ȯ",Ȱ:"Ȱ",Ő:"Ő",Ṕ:"Ṕ",Ṗ:"Ṗ",Ŕ:"Ŕ",Ř:"Ř",Ṙ:"Ṙ",Ŗ:"Ŗ",Ś:"Ś",Ṥ:"Ṥ",Š:"Š",Ṧ:"Ṧ",Ŝ:"Ŝ",Ṡ:"Ṡ",Ş:"Ş",Ť:"Ť",Ṫ:"Ṫ",Ţ:"Ţ",Ú:"Ú",Ù:"Ù",Ü:"Ü",Ǘ:"Ǘ",Ǜ:"Ǜ",Ǖ:"Ǖ",Ǚ:"Ǚ",Ũ:"Ũ",Ṹ:"Ṹ",Ū:"Ū",Ṻ:"Ṻ",Ŭ:"Ŭ",Ǔ:"Ǔ",Û:"Û",Ů:"Ů",Ű:"Ű",Ṽ:"Ṽ",Ẃ:"Ẃ",Ẁ:"Ẁ",Ẅ:"Ẅ",Ŵ:"Ŵ",Ẇ:"Ẇ",Ẍ:"Ẍ",Ẋ:"Ẋ",Ý:"Ý",Ỳ:"Ỳ",Ÿ:"Ÿ",Ỹ:"Ỹ",Ȳ:"Ȳ",Ŷ:"Ŷ",Ẏ:"Ẏ",Ź:"Ź",Ž:"Ž",Ẑ:"Ẑ",Ż:"Ż",ά:"ά",ὰ:"ὰ",ᾱ:"ᾱ",ᾰ:"ᾰ",έ:"έ",ὲ:"ὲ",ή:"ή",ὴ:"ὴ",ί:"ί",ὶ:"ὶ",ϊ:"ϊ",ΐ:"ΐ",ῒ:"ῒ",ῑ:"ῑ",ῐ:"ῐ",ό:"ό",ὸ:"ὸ",ύ:"ύ",ὺ:"ὺ",ϋ:"ϋ",ΰ:"ΰ",ῢ:"ῢ",ῡ:"ῡ",ῠ:"ῠ",ώ:"ώ",ὼ:"ὼ",Ύ:"Ύ",Ὺ:"Ὺ",Ϋ:"Ϋ",Ῡ:"Ῡ",Ῠ:"Ῠ",Ώ:"Ώ",Ὼ:"Ὼ"};class wg{constructor(e,t){this.mode="math",this.gullet=new d1e(e,t,this.mode),this.settings=t,this.leftrightDepth=0,this.nextToken=null}expect(e,t){if(t===void 0&&(t=!0),this.fetch().text!==e)throw new Ae("Expected '"+e+"', got '"+this.fetch().text+"'",this.fetch());t&&this.consume()}consume(){this.nextToken=null}fetch(){return this.nextToken==null&&(this.nextToken=this.gullet.expandNextToken()),this.nextToken}switchMode(e){this.mode=e,this.gullet.switchMode(e)}parse(){this.settings.globalGroup||this.gullet.beginGroup(),this.settings.colorIsTextColor&&this.gullet.macros.set("\\color","\\textcolor");try{var e=this.parseExpression(!1);return this.expect("EOF"),this.settings.globalGroup||this.gullet.endGroup(),e}finally{this.gullet.endGroups()}}subparse(e){var t=this.nextToken;this.consume(),this.gullet.pushToken(new Rr("}")),this.gullet.pushTokens(e);var s=this.parseExpression(!1);return this.expect("}"),this.nextToken=t,s}parseExpression(e,t){for(var s=[];;){this.mode==="math"&&this.consumeSpaces();var r=this.fetch();if(wg.endOfExpression.has(r.text)||t&&r.text===t||e&&Qo[r.text]&&Qo[r.text].infix)break;var i=this.parseAtom(t);if(i){if(i.type==="internal")continue}else break;s.push(i)}return this.mode==="text"&&this.formLigatures(s),this.handleInfixNodes(s)}handleInfixNodes(e){for(var t=-1,s,r=0;r=128)this.settings.strict&&(gA(t.charCodeAt(0))?this.mode==="math"&&this.settings.reportNonstrict("unicodeTextInMathMode",'Unicode text character "'+t[0]+'" used in math mode',e):this.settings.reportNonstrict("unknownSymbol",'Unrecognized Unicode character "'+t[0]+'"'+(" ("+t.charCodeAt(0)+")"),e)),o={type:"textord",mode:"text",loc:hr.range(e),text:t};else return null;if(this.consume(),i)for(var h=0;hthis.toggle()),this.scrim.addEventListener("click",()=>this.toggle()),window.addEventListener("keydown",t=>{t.key==="Escape"&&this.open&&this.toggle()})}toggle(){this.open=!this.open,this.drawer.style.transform=this.open?"translateX(0)":"translateX(100%)",this.scrim.style.opacity=this.open?"1":"0",this.scrim.style.pointerEvents=this.open?"auto":"none",this.btn.textContent=this.open?"× close":"? how it works"}}function dR(n,e){const t=document.createElement(e?"div":"span");return v1e.render(n,t,{displayMode:e,throwOnError:!1,errorColor:"#ff6666",strict:"ignore",trust:!1,output:"html"}),t}function V1(n){return n.map(e=>{if(typeof e=="string")return document.createTextNode(e);if(e instanceof HTMLElement)return e;if(e.tag==="math-inline")return dR(e.latex,!1);const t=document.createElement(e.tag);return t.textContent=e.text,t})}function W1(n,e){for(const t of e)n.appendChild(t)}function w1e(){const n=document.createElement("div");n.className="info";const e=document.createElement("h1");e.textContent="neuron-runner",n.appendChild(e);const t=document.createElement("p");t.className="sub",t.textContent="A tiny neural net learning a platformer. Training, inference, and visualization all run locally in your browser on WebGPU — no server, no Python, no hidden layer of magic.",n.appendChild(t);for(const s of S1e)switch(s.kind){case"h":{const r=document.createElement("h2");r.textContent=s.text,n.appendChild(r);break}case"p":{const r=document.createElement("p");W1(r,V1(s.parts)),n.appendChild(r);break}case"ul":{const r=document.createElement("ul");for(const i of s.items){const o=document.createElement("li");W1(o,V1(i)),r.appendChild(o)}n.appendChild(r);break}case"math":{const r=document.createElement("div");r.className="mathblock",r.appendChild(dR(s.latex,!0)),n.appendChild(r);break}case"note":{const r=document.createElement("div");r.className="note",W1(r,V1(s.parts)),n.appendChild(r);break}case"hr":{n.appendChild(document.createElement("hr"));break}}return n}const Lt=n=>({tag:"em",text:n}),ys=n=>({tag:"code",text:n}),_t=n=>({tag:"math-inline",latex:n}),S1e=[{kind:"h",text:"1. What you're looking at"},{kind:"p",parts:[Lt("Right panel")," — a 2D platformer with a Mario-ish agent that must reach the flag on the right side. Falling off the level kills it."]},{kind:"p",parts:[Lt("Left panel")," — a live visualization of the neural network that decides, 60 times per second, what the agent should do next. The network is small enough that you can see every neuron fire in real time. You can swap between ",Lt("two architectures")," — a standard MLP and a continued-fraction-based ",Lt("CoFrNet")," — using the ",ys("brain:")," dropdown in the footer, and the visualization changes to match."]},{kind:"p",parts:[Lt("Bottom")," — controls (seed, reset, pause) and two sparklines: total reward per episode (green) and training loss per update (amber)."]},{kind:"h",text:"2. The game"},{kind:"p",parts:["Each game tick (1/60 s) the agent observes the world, picks an action, and the world updates."]},{kind:"p",parts:[Lt("Actions")," (4 discrete): ",ys("noop"),", ",ys("left"),", ",ys("right"),", ",ys("jump"),". ",ys("jump")," only has an effect when on the ground."]},{kind:"p",parts:[Lt("Physics"),": constant gravity, horizontal impulses on left / right, friction on contact, a single fixed jump impulse."]},{kind:"p",parts:["The reward signal ",_t("r_t")," at each step is:"]},{kind:"ul",items:[[_t("+1")," on reaching the goal (episode ends)"],[_t("-1")," on falling below the death line (episode ends)"],[_t("+0.01 \\cdot \\Delta x")," each tick for rightward progress (shaping signal)"],[_t("-0.2")," if the episode exceeds 1500 ticks without terminating"]]},{kind:"h",text:"3. The observation"},{kind:"p",parts:["Each tick the network sees a 24-dimensional vector ",_t("s_t \\in \\mathbb{R}^{24}")," summarizing the world:"]},{kind:"ul",items:[[Lt("Dims 0–3")," agent state: normalized ",_t("x,\\; y,\\; v_x,\\; v_y")],[Lt("Dims 4–15")," next 4 platforms ahead: ",_t("(\\Delta x,\\; y,\\; w)")," for each"],[Lt("Dims 16–23")," next 4 gaps ahead: ",_t("(\\Delta x,\\; w)")," for each"]]},{kind:"p",parts:["No raw pixels. Hand-crafted features keep the problem tractable for a 2-layer MLP and keep the visualization legible: each input neuron corresponds to one real thing in the world."]},{kind:"h",text:"4. Two swappable architectures"},{kind:"p",parts:["The ",ys("brain:")," dropdown in the footer switches between two policy networks. Both take the same 24-dim observation, produce the same 4-action distribution, and are trained by the same REINFORCE loop — they differ only in the function they compute between input and logits."]},{kind:"h",text:"4a. MLP (the default)"},{kind:"p",parts:["A 2-layer multi-layer perceptron with a tanh nonlinearity and a softmax output:"]},{kind:"math",latex:`\\begin{aligned} +h &= \\tanh\\bigl(W_1\\, s + b_1\\bigr), & W_1 &\\in \\mathbb{R}^{24 \\times 64},\\; b_1 \\in \\mathbb{R}^{64} \\\\[2pt] +z &= W_2\\, h + b_2, & W_2 &\\in \\mathbb{R}^{64 \\times 4},\\; b_2 \\in \\mathbb{R}^{4} \\\\[2pt] +\\pi(a \\mid s) &= \\operatorname{softmax}(z) +\\end{aligned}`},{kind:"p",parts:["Softmax turns the raw logits into a probability distribution over the 4 actions:"]},{kind:"math",latex:"\\operatorname{softmax}(z)_i \\;=\\; \\frac{\\exp(z_i)}{\\sum_j \\exp(z_j)}"},{kind:"p",parts:["Parameter count: ",_t("24 \\cdot 64 + 64 + 64 \\cdot 4 + 4 = 1\\,860"),". Fast, expressive, standard."]},{kind:"h",text:"4b. CoFrNet (continued fractions)"},{kind:"p",parts:["An IBM Research architecture (Puri et al., NeurIPS 2021) where each action's logit is produced by a ",Lt("continued-fraction ladder"),". We use ",_t("L = 4")," ladders (one per action) at depth ",_t("d = 8"),", each reading the full observation at every rung:"]},{kind:"math",latex:"f_\\ell(x) \\;=\\; a_{\\ell,0} + \\cfrac{1}{a_{\\ell,1} + \\cfrac{1}{a_{\\ell,2} + \\cfrac{1}{\\ddots + \\cfrac{1}{a_{\\ell,d}}}}}"},{kind:"p",parts:["where each rung is a linear function of the raw input: ",_t("a_{\\ell,k} = W_{\\ell,k}^\\top x + b_{\\ell,k}"),". Evaluated bottom-up:"]},{kind:"math",latex:"V_{\\ell, d} = a_{\\ell, d}, \\qquad V_{\\ell, k} = a_{\\ell, k} + \\operatorname{saferecip}(V_{\\ell, k+1})"},{kind:"p",parts:["The action logits are the top-rung values: ",_t("\\operatorname{logits}_\\ell = V_{\\ell, 0}"),", and ",_t("\\pi = \\operatorname{softmax}(\\operatorname{logits})")," as before."]},{kind:"p",parts:["Poles (where a denominator approaches zero) are mitigated by a smooth bounded reciprocal:"]},{kind:"math",latex:"\\operatorname{saferecip}(v) \\;=\\; \\frac{v}{v^2 + \\varepsilon^2}, \\qquad \\varepsilon = 0.1"},{kind:"note",parts:[Lt("Deviation from the paper: "),"Puri et al. use ",_t("\\operatorname{sign}(v) / \\max(|v|, \\varepsilon)"),", which has a kink at ",_t("|v| = \\varepsilon")," that interacted badly with Adam + policy-gradient variance in our setup (action probabilities would climb to 0.999 and then crash to 0.0003 the next episode). The smooth form above is differentiable everywhere, has bounded gradients, and converges cleanly."]},{kind:"p",parts:["Parameter count: ",_t("L (d+1) p + L (d+1) = 4 \\cdot 9 \\cdot 24 + 4 \\cdot 9 = 900")," — less than half the MLP."]},{kind:"h",text:"Why both?"},{kind:"p",parts:["The MLP is the baseline. The CoFrNet is ",Lt("interpretable by construction"),`: because every rung's coefficients are a linear function of the raw input (not of some hidden activation like in an MLP), you can look at the output rung's weights and directly read which input features matter for each action. The feature-attribution panel at the bottom of the CoFrNet viz is exactly that readout — live. That's what the authors of the paper mean by "interpretable-by-construction," and it's the whole reason to bother with the fancier functional form.`]},{kind:"h",text:"5. Sampling an action"},{kind:"p",parts:["The policy is stochastic. Each tick we sample:"]},{kind:"math",latex:"a_t \\;\\sim\\; \\pi(\\,\\cdot \\mid s_t\\,)"},{kind:"p",parts:["Concretely: draw ",_t("u \\sim \\mathrm{Uniform}(0,1)"),", walk the cumulative sum of ",_t("\\pi"),", pick the first index whose cumsum exceeds ",_t("u"),". This is why the same state can produce different actions — the agent is exploring, not deterministic."]},{kind:"h",text:"6. How the network learns — REINFORCE"},{kind:"p",parts:["At the end of each episode (goal, death, or timeout), we do one gradient step that nudges the network to make the actions we just took ",Lt("more likely")," when they led to high reward, and ",Lt("less likely")," when they led to low reward."]},{kind:"p",parts:["The per-step signal is the ",Lt("return")," — the discounted sum of future rewards from time ",_t("t"),":"]},{kind:"math",latex:"R_t \\;=\\; \\sum_{i=t}^{T} \\gamma^{\\,i-t}\\, r_i, \\qquad \\gamma = 0.99"},{kind:"p",parts:["The objective we maximize is expected return under the policy, ",_t("J(\\theta) = \\mathbb{E}_{\\pi_\\theta}\\!\\left[\\sum_t r_t\\right]"),". The REINFORCE gradient estimator is:"]},{kind:"math",latex:"\\nabla_\\theta J(\\theta) \\;\\approx\\; \\sum_{t=0}^{T} \\nabla_\\theta \\log \\pi_\\theta(a_t \\mid s_t) \\,\\bigl(R_t - b\\bigr)"},{kind:"p",parts:["...where ",_t("b")," is a ",Lt("baseline")," subtracted to reduce variance without biasing the estimate. Classical choices are a running mean of episode returns, or a learned value function ",_t("V_\\phi(s)"),"."]},{kind:"p",parts:["In code we implement this as a loss to ",Lt("minimize"),":"]},{kind:"math",latex:"\\mathcal{L}(\\theta) \\;=\\; -\\sum_{t=0}^{T} \\log \\pi_\\theta(a_t \\mid s_t) \\,\\bigl(R_t - b\\bigr)"},{kind:"p",parts:["One Adam step (learning rate ",_t("3 \\times 10^{-3}"),") per episode."]},{kind:"note",parts:[Lt("Implementation caveat: "),"the current code uses ",_t("b = 0")," (raw returns as advantages) rather than the running-mean baseline the spec prescribed. The baseline was dropped during implementation because, on the deterministic unit test, the mean-of-episode-total baseline pushed action probabilities the wrong way. Real training still works — it's just higher variance than it would be with a proper per-step baseline. A value-function baseline (actor-critic) would be the natural upgrade."]},{kind:"h",text:"7. Reading the visualizations"},{kind:"p",parts:["The left panel renders a different view depending on which architecture is active."]},{kind:"h",text:"7a. MLP mode"},{kind:"p",parts:["Three vertical columns of circles, ",Lt("left to right:")]},{kind:"ul",items:[[Lt("Input layer")," (24 circles) — the current observation ",_t("s"),". Radius ∝ ",_t("|s_i|"),". Green = positive, pink = negative."],[Lt("Hidden layer")," (64 circles, 8×8 grid) — the tanh activations ",_t("h"),". Same coloring; brightness ∝ ",_t("|h_i|"),"."],[Lt("Output layer")," (4 circles) — the action probabilities ",_t("\\pi"),". The argmax glows brightest; its label appears in the top-right corner of the panel."]]},{kind:"p",parts:[Lt("Edges")," between layers are rendered with opacity proportional to the instantaneous contribution of one neuron to the next:"]},{kind:"math",latex:"\\alpha(i, j) \\;=\\; \\operatorname{clip}\\!\\bigl(\\,|\\,a_i \\cdot w_{ij}\\,|,\\; 0,\\; 1\\bigr)"},{kind:"p",parts:["...so the lines you see lit up are the ",Lt("currently active pathways"),": pairs where the source neuron's activation is large ",Lt("and")," the connecting weight is large. Dim edges mean that connection isn't doing much for this particular input."]},{kind:"h",text:"7b. CoFrNet mode"},{kind:"p",parts:["Four color-coded ladder columns — ",ys("noop")," (slate), ",ys("left")," (crimson), ",ys("right")," (green), ",ys("jump")," (amber) — each showing the ",_t("d + 1 = 9")," rungs of its continued fraction, with ",_t("k = 0")," at the top (the output logit) and ",_t("k = d = 8")," at the bottom."]},{kind:"ul",items:[[Lt("Rung discs"),": size ∝ ",_t("|a_{\\ell, k}|"),". Disc color is the ladder's color when ",_t("a_{\\ell, k} \\ge 0"),", rose when negative."],[Lt("Probability bars")," at the top of each column show ",_t("\\pi_\\ell")," live, with the percentage below."],[Lt("The hot ladder")," (the argmax action) has a brighter backdrop, a bolded label, haloed rungs, and an ",_t("a_0")," readout next to its top rung."],[Lt("Upward arrows")," between rungs brighten with ",_t("|\\operatorname{saferecip}(V_{\\ell, k+1})|")," — the magnitude of the reciprocal term flowing up through the fraction. Bright arrows = the hot path through the CF."],[Lt("The traveling pulse")," on each column is decorative, a reminder that the CF is evaluated bottom-up."]]},{kind:"h",text:"7c. Feature attribution (CoFrNet only)"},{kind:"p",parts:["The footer of the CoFrNet viz answers the question ",Lt("why did the agent pick this action?")," Let ",_t("\\ell^\\ast = \\arg\\max_\\ell \\pi_\\ell")," be the chosen action. Since the output rung of its ladder is the linear term ",_t("a_{\\ell^\\ast, 0} = W_{\\ell^\\ast, 0}^\\top x + b_{\\ell^\\ast, 0}"),", the contribution of input feature ",_t("j")," to the output is directly ",_t("W_{\\ell^\\ast, 0, j} \\cdot x_j"),". The panel ranks features by:"]},{kind:"math",latex:"\\text{contribution}_j \\;=\\; |\\, W_{\\ell^\\ast, 0, j} \\cdot x_j \\,|"},{kind:"p",parts:["and shows the top 5 as horizontal bars with their real names (",ys("plat1.dx"),", ",ys("gap2.w"),", etc.). Bar color is the ladder's color when the signed contribution is positive, rose when negative. This is the interpretability payoff: you see ",Lt("in real time")," which pieces of the world are driving the decision the agent just took."]},{kind:"h",text:"8. What to expect over time"},{kind:"ul",items:[[Lt("Episodes 0–10.")," The policy is ~uniform random. The agent wanders, falls off a lot. Reward per episode hovers near zero or slightly negative."],[Lt("Episodes 10–50.")," The shaping reward ",_t("+0.01 \\cdot \\Delta x"),` biases the policy toward "move right." You'll see rightward momentum build. The reward sparkline starts trending up.`],[Lt("Episodes 50–200.")," The agent learns ",Lt("when")," to jump by associating gap features (dims 16–23) with the jump action. Occasionally it clears the level."],[Lt("Episodes 200+.")," The policy stabilizes. The agent clears most levels reliably on the fixed seed. Change the seed from the footer and it'll take a while to adapt to the new layout — the net generalizes, but only moderately on this small an architecture."]]},{kind:"hr"},{kind:"h",text:"Running notes"},{kind:"p",parts:[Lt("Backend"),": TensorFlow.js 4.x with its WebGPU backend. Every matrix multiply in the forward pass (",_t("24 \\to 64"),", ",_t("64 \\to 4"),") and every gradient in the backward pass runs as a WebGPU compute shader. Change the seed + Reset to spawn a fresh network on a fresh level."]},{kind:"p",parts:["Design specs: ",ys("docs/superpowers/specs/2026-04-20-neuron-runner-design.md")," (base project), ",ys("docs/superpowers/specs/2026-04-20-cofrnet-integration.md")," (CoFrNet integration). Implementation plans live in the sibling ",ys("plans/")," directory. Both were generated collaboratively with Claude and executed by a Ralph loop."]},{kind:"p",parts:["CoFrNet paper: Puri, Dhurandhar, Pedapati, Shanmugam, Wei, Varshney, ",Lt("CoFrNets: Interpretable Neural Architecture Inspired by Continued Fractions"),", NeurIPS 2021 — ",ys("arxiv.org/abs/2506.05586"),"."]},{kind:"p",parts:["Press ",ys("Esc")," or click outside to close."]}];async function C1e(){try{return await Zb("webgpu"),await Jb(),"webgpu"}catch(n){return console.warn("WebGPU unavailable, falling back to CPU:",n),await Zb("cpu"),await Jb(),"cpu"}}function HS(n){return n==="mlp"?new Cme:new _me}async function _1e(){const n=await C1e(),e=document.getElementById("viz-panel"),t=document.getElementById("game-panel"),s=document.getElementById("stats-footer");let r=1,i=!1,o=0,a="mlp",l=0;const c=new oue;c.reset(r);let u=HS(a),h=new uS(u);const d=new Sme(t),p=new Tme(e),f=new kme(e),x=new Ame(s,{onReset:v=>{r=v|0,c.reset(r),h.startEpisode(),o=0},onTogglePause:()=>(i=!i,i),onArchChange:v=>{v!==a&&(a=v,h.startEpisode(),u.dispose(),u=HS(a),h=new uS(u),c.reset(r),o=0,l=0,h.startEpisode())}});new y1e,h.startEpisode();let m=0;async function g(){if(m+=1,!i){const v=c.obs(),b=Zs(v),y=u.forward(b),w=y.probs.dataSync(),C=Math.random();let T=0,E=0;for(let _=0;_P&&(P=w[L],M=L);f.draw({obs:v,A:_,V:k,W:B,probs:w,argmax:M})}d.draw(c),R.done&&(h.endEpisode(),x.pushEpisodeReward(l),x.pushLoss(h.lastLoss),o+=1,l=0,c.reset(r+o),h.startEpisode()),Nt([b,y.probs]),y.activations.kind==="mlp"?Nt([y.activations.hidden]):Nt([y.activations.A,y.activations.V])}m%15===0&&(x.setStatus(`backend=${n} | arch=${a} | episode=${o} | tensors=${tx().numTensors}`),x.draw()),requestAnimationFrame(g)}requestAnimationFrame(g)}_1e().catch(n=>{console.error(n);const e=document.getElementById("stats-footer");e&&(e.textContent=`ERROR: ${String(n)}`)}); diff --git a/assets/index-Wcl8nPQ0.css b/assets/index-Wcl8nPQ0.css new file mode 100644 index 0000000000000000000000000000000000000000..51be82278247f07fe8e2a8158d65a3fb52c76fe8 --- /dev/null +++ b/assets/index-Wcl8nPQ0.css @@ -0,0 +1 @@ +*{box-sizing:border-box;margin:0;padding:0}html,body,#app{height:100%;width:100%;background:#0a0a0f;color:#eee;font-family:ui-monospace,Menlo,Consolas,monospace}#app{display:grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 120px;grid-template-areas:"viz game" "stats stats";gap:1px;background:#222}#viz-panel{grid-area:viz;background:#0a0a0f;position:relative;min-height:0;min-width:0;overflow:hidden}#game-panel{grid-area:game;background:#101018;position:relative;min-height:0;min-width:0;overflow:hidden}#stats-footer{grid-area:stats;background:#0a0a0f;padding:8px;min-width:0;overflow:hidden}canvas{display:block;width:100%;height:100%}@font-face{font-display:block;font-family:KaTeX_AMS;font-style:normal;font-weight:400;src:url(/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2) format("woff2"),url(/assets/KaTeX_AMS-Regular-DMm9YOAa.woff) format("woff"),url(/assets/KaTeX_AMS-Regular-DRggAlZN.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Caligraphic;font-style:normal;font-weight:700;src:url(/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2) format("woff2"),url(/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff) format("woff"),url(/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Caligraphic;font-style:normal;font-weight:400;src:url(/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2) format("woff2"),url(/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff) format("woff"),url(/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Fraktur;font-style:normal;font-weight:700;src:url(/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2) format("woff2"),url(/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff) format("woff"),url(/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Fraktur;font-style:normal;font-weight:400;src:url(/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2) format("woff2"),url(/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff) format("woff"),url(/assets/KaTeX_Fraktur-Regular-CB_wures.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Main;font-style:normal;font-weight:700;src:url(/assets/KaTeX_Main-Bold-Cx986IdX.woff2) format("woff2"),url(/assets/KaTeX_Main-Bold-Jm3AIy58.woff) format("woff"),url(/assets/KaTeX_Main-Bold-waoOVXN0.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Main;font-style:italic;font-weight:700;src:url(/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2) format("woff2"),url(/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff) format("woff"),url(/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Main;font-style:italic;font-weight:400;src:url(/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2) format("woff2"),url(/assets/KaTeX_Main-Italic-BMLOBm91.woff) format("woff"),url(/assets/KaTeX_Main-Italic-3WenGoN9.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Main;font-style:normal;font-weight:400;src:url(/assets/KaTeX_Main-Regular-B22Nviop.woff2) format("woff2"),url(/assets/KaTeX_Main-Regular-Dr94JaBh.woff) format("woff"),url(/assets/KaTeX_Main-Regular-ypZvNtVU.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Math;font-style:italic;font-weight:700;src:url(/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2) format("woff2"),url(/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff) format("woff"),url(/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Math;font-style:italic;font-weight:400;src:url(/assets/KaTeX_Math-Italic-t53AETM-.woff2) format("woff2"),url(/assets/KaTeX_Math-Italic-DA0__PXp.woff) format("woff"),url(/assets/KaTeX_Math-Italic-flOr_0UB.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_SansSerif;font-style:normal;font-weight:700;src:url(/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2) format("woff2"),url(/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff) format("woff"),url(/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_SansSerif;font-style:italic;font-weight:400;src:url(/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2) format("woff2"),url(/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff) format("woff"),url(/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_SansSerif;font-style:normal;font-weight:400;src:url(/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2) format("woff2"),url(/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff) format("woff"),url(/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Script;font-style:normal;font-weight:400;src:url(/assets/KaTeX_Script-Regular-D3wIWfF6.woff2) format("woff2"),url(/assets/KaTeX_Script-Regular-D5yQViql.woff) format("woff"),url(/assets/KaTeX_Script-Regular-C5JkGWo-.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Size1;font-style:normal;font-weight:400;src:url(/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2) format("woff2"),url(/assets/KaTeX_Size1-Regular-C195tn64.woff) format("woff"),url(/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Size2;font-style:normal;font-weight:400;src:url(/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2) format("woff2"),url(/assets/KaTeX_Size2-Regular-oD1tc_U0.woff) format("woff"),url(/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Size3;font-style:normal;font-weight:400;src:url(data:font/woff2;base64,d09GMgABAAAAAA4oAA4AAAAAHbQAAA3TAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAAgRQIDgmcDBEICo1oijYBNgIkA14LMgAEIAWJAAeBHAyBHBvbGiMRdnO0IkRRkiYDgr9KsJ1NUAf2kILNxgUmgqIgq1P89vcbIcmsQbRps3vCcXdYOKSWEPEKgZgQkprQQsxIXUgq0DqpGKmIvrgkeVGtEQD9DzAO29fM9jYhxZEsL2FeURH2JN4MIcTdO049NCVdxQ/w9NrSYFEBKTDKpLKfNkCGDc1RwjZLQcm3vqJ2UW9Xfa3tgAHz6ivp6vgC2yD4/6352ndnN0X0TL7seypkjZlMsjmZnf0Mm5Q+JykRWQBKCVCVPbARPXWyQtb5VgLB6Biq7/Uixcj2WGqdI8tGSgkuRG+t910GKP2D7AQH0DB9FMDW/obJZ8giFI3Wg8Cvevz0M+5m0rTh7XDBlvo9Y4vm13EXmfttwI4mBo1EG15fxJhUiCLbiiyCf/ZA6MFAhg3pGIZGdGIVjtPn6UcMk9A/UUr9PhoNsCENw1APAq0gpH73e+M+0ueyHbabc3vkbcdtzcf/fiy+NxQEjf9ud/ELBHAXJ0nk4z+MXH2Ev/kWyV4k7SkvpPc9Qr38F6RPWnM9cN6DJ0AdD1BhtgABtmoRoFCvPsBAumNm6soZG2Gk5GyVTo2sJncSyp0jQTYoR6WDvTwaaEcHsxHfvuWhHA3a6bN7twRKtcGok6NsCi7jYRrM2jExsUFMxMQYuJbMhuWNOumEJy9hi29Dmg5zMp/A5+hhPG19j1vBrq8JTLr8ki5VLPmG/PynJHVul440bxg5xuymHUFPBshC+nA9I1FmwbRBTNHAcik3Oae0cxKoI3MOriM42UrPe51nsaGxJ+WfXubAsP84aabUlQSJ1IiE0iPETLUU4CATgfXSCSpuRFRmCGbO+wSpAnzaeaCYW1VNEysRtuXCEL1kUFUbbtMv3Tilt/1c11jt3Q5bbMa84cpWipp8Elw3MZhOHsOlwwVUQM3lAR35JiFQbaYCRnMF2lxAWoOg2gyoIV4PouX8HytNIfLhqpJtXB4vjiViUI8IJ7bkC4ikkQvKksnOTKICwnqWSZ9YS5f0WCxmpgjbIq7EJcM4aI2nmhLNY2JIUgOjXZFWBHb+x5oh6cwb0Tv1ackHdKi0I9OO2wE9aogIOn540CCCziyhN+IaejtgAONKznHlHyutPrHGwCx9S6B8kfS4Mfi4Eyv7OU730bT1SCBjt834cXsf43zVjPUqqJjgrjeGnBxSG4aYAKFuVbeCfkDIjAqMb6yLNIbCuvXhMH2/+k2vkNpkORhR59N1CkzoOENvneIosjYmuTxlhUzaGEJQ/iWqx4dmwpmKjrwTiTGTCVozNAYqk/zXOndWxuWSmJkQpJw3pK5KX6QrLt5LATMqpmPAQhkhK6PUjzHUn7E0gHE0kPE0iKkolgkUx9SZmVAdDgpffdyJKg3k7VmzYGCwVXGz/tXmkOIp+vcWs+EMuhhvN0h9uhfzWJziBQmCREGSIFmQIkgVpAnSBRmC//6hkLZwaVhwxlrJSOdqlFtOYxlau9F2QN5Y98xmIAsiM1HVp2VFX+DHHGg6Ecjh3vmqtidX3qHI2qycTk/iwxSt5UzTmEP92ZBnEWTk4Mx8Mpl78ZDokxg/KWb+Q0QkvdKVmq3TMW+RXEgrsziSAfNXFMhDc60N5N9jQzjfO0kBKpUZl0ZmwJ41j/B9Hz6wmRaJB84niNmQrzp9eSlQCDDzazGDdVi3P36VZQ+Jy4f9UBNp+3zTjqI4abaFAm+GShVaXlsGdF3FYzZcDI6cori4kMxUECl9IjJZpzkvitAoxKue+90pDMvcKRxLl53TmOKCmV/xRolNKSqqUxc6LStOETmFOiLZZptlZepcKiAzteG8PEdpnQpbOMNcMsR4RR2Bs0cKFEvSmIjAFcnarqwUL4lDhHmnVkwu1IwshbiCcgvOheZuYyOteufZZwlcTlLgnZ3o/WcYdzZHW/WGaqaVfmTZ1aWCceJjkbZqsfbkOtcFlUZM/jy+hXHDbaUobWqqXaeWobbLO99yG5N3U4wxco0rQGGcOLASFMXeJoham8M+/x6O2WywK2l4HGbq1CoUyC/IZikQhdq3SiuNrvAEj0AVu9x2x3lp/xWzahaxidezFVtdcb5uEnzyl0ZmYiuKI0exvCd4Xc9CV1KB0db00z92wDPde0kukbvZIWN6jUWFTmPIC/Y4UPCm8UfDTFZpZNon1qLFTkBhxzB+FjQRA2Q/YRJT8pQigslMaUpFyAG8TMlXigiqmAZX4xgijKjRlGpLE0GdplRfCaJo0JQaSxNBk6ZmMzcya0FmrcisDdn0Q3HI2sWSppYigmlM1XT/kLQZSNpMJG0WkjYbSZuDpM1F0uYhFc1HxU4m1QJjDK6iL0S5uSj5rgXc3RejEigtcRBtqYPQsiTskmO5vosV+q4VGIKbOkDg0jtRrq+Em1YloaTFar3EGr1EUC8R0kus1Uus00usL97ABr2BjXoDm/QGNhuWtMVBKOwg/i78lT7hBsAvDmwHc/ao3vmUbBmhjeYySZNWvGkfZAgISDSaDo1SVpzGDsAEkF8B+gEapViUoZgUWXcRIGFZNm6gWbAKk0bp0k1MHG9fLYtV4iS2SmLEQFARzRcnf9PUS0LVn05/J9MiRRBU3v2IrvW974v4N00L7ZMk0wXP1409CHo/an8zTRHD3eSJ6m8D4YMkZNl3M79sqeuAsr/m3f+8/yl7A50aiAEJgeBeMWzu7ui9UfUBCe2TIqZIoOd/3/udRBOQidQZUERzb2/VwZN1H/Sju82ew2H2Wfr6qvfVf3hqwDvAIpkQVFy4B9Pe9e4/XvPeceu7h3dvO56iJPf0+A6cqA2ip18ER+iFgggiuOkvj24bby0N9j2UHIkgqIt+sVgfodC4YghLSMjSZbH0VR/6dMDrYJeKHilKTemt6v6kvzvn3/RrdWtr0GoN/xL+Sex/cPYLUpepx9cz/D46UPU5KXgAQa+NDps1v6J3xP1i2HtaDB0M9aX2deA7SYff//+gUCovMmIK/qfsFcOk+4Y5ZN97XlG6zebqtMbKgeRFi51vnxTQYBUik2rS/Cn6PC8ADR8FGxsRPB82dzfND90gIcshOcYUkfjherBz53odpm6TP8txlwOZ71xmfHHOvq053qFF/MRlS3jP0ELudrf2OeN8DHvp6ZceLe8qKYvWz/7yp0u4dKPfli3CYq0O13Ih71mylJ80tOi10On8wi+F4+LWgDPeJ30msSQt9/vkmHq9/Lvo2b461mP801v3W4xTcs6CbvF9UDdrSt+A8OUbpSh55qAUFXWznBBfdeJ8a4d7ugT5tvxUza3h9m4H7ptTqiG4z0g5dc0X29OcGlhpGFMpQo9ytTS+NViZpNdvU4kWx+LKxNY10kQ1yqGXrhe4/1nvP7E+nd5A92TtaRplbHSqoIdOqtRWti+fkB5/n1+/VvCmz12pG1kpQWsfi1ftlBobm0bpngs16CHkbIwdLnParxtTV3QYRlfJ0KFskH7pdN/YDn+yRuSd7sNH3aO0DYPggk6uWuXrfOc+fa3VTxFVvKaNxHsiHmsXyCLIE5yuOeN3/Jdf8HBL/5M6shjyhxHx9BjB1O0+4NLOnjLLSxwO7ukN4jMbOIcD879KLSi6Pk61Oqm2377n8079PXEEQ7cy7OKEC9nbpet118fxweTafpt69x/Bt8UqGzNQt7aelpc44dn5cqhwf71+qKp/Zf/+a0zcizOUWpl/iBcSXip0pplkatCchoH5c5aUM8I7/dWxAej8WicPL1URFZ9BDJelUwEwTkGqUhgSlydVes95YdXvhh9Gfz/aeFWvgVb4tuLbcv4+wLdutVZv/cUonwBD/6eDlE0aSiKK/uoH3+J1wDE/jMVqY2ysGufN84oIXB0sPzy8ollX/LegY74DgJXJR57sn+VGza0x3DnuIgABFM15LmajjjsNlYj+JEZGbuRYcAMOWxFkPN2w6Wd46xo4gVWQR/X4lyI/R6K/YK0110GzudPRW7Y+UOBGTfNNzHeYT0fiH0taunBpq9HEW8OKSaBGj21L0MqenEmNRWBAWDWAk4CpNoEZJ2tTaPFgbQYj8HxtFilErs3BTRwT8uO1NXQaWfIotchmPkAF5mMBAliEmZiOGVgCG9LgRzpscMAOOwowlT3JhusdazXGSC/hxR3UlmWVwWHpOIKheqONvjyhSiTHIkVUco5bnji8m//zL7PKaT1Vl5I6UE609f+gkr6MZKVyKc7zJRmCahLsdlyA5fdQkRSan9LgnnLEyGSkaKJCJog0wAgvepWBt80+1yKln1bMVtCljfNWDueKLsWwaEbBSfSPTEmVRsUcYYMnEjcjeyCZzBXK9E9BYBXLKjOSpUDR+nEV3TFSUdQaz+ot98QxgXwx0GQ+EEUAKB2qZPkQQ0GqFD8UPFMqyaCHM24BZmSGic9EYMagKizOw9Hz50DMrDLrqqLkTAhplMictiCAx5S3BIUQdeJeLnBy2CNtMfz6cV4u8XKoFZQesbf9YZiIERiHjaNodDW6LgcirX/mPnJIkBGDUpTBhSa0EIr38D5hCIszhCM8URGBqImoWjpvpt1ebu/v3Gl3qJfMnNM+9V+kiRFyROTPHQWOcs1dNW94/ukKMPZBvDi55i5CttdeJz84DLngLqjcdwEZ87bFFR8CIG35OAkDVN6VRDZ7aq67NteYqZ2lpT8oYB2CytoBd6VuAx4WgiAsnuj3WohG+LugzXiQRDeM3XYXlULv4dp5VFYC) format("woff2"),url(/assets/KaTeX_Size3-Regular-CTq5MqoE.woff) format("woff"),url(/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Size4;font-style:normal;font-weight:400;src:url(/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2) format("woff2"),url(/assets/KaTeX_Size4-Regular-BF-4gkZK.woff) format("woff"),url(/assets/KaTeX_Size4-Regular-DWFBv043.ttf) format("truetype")}@font-face{font-display:block;font-family:KaTeX_Typewriter;font-style:normal;font-weight:400;src:url(/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2) format("woff2"),url(/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff) format("woff"),url(/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf) format("truetype")}.katex{font: 1.21em KaTeX_Main,Times New Roman,serif;line-height:1.2;position:relative;text-indent:0;text-rendering:auto}.katex *{-ms-high-contrast-adjust:none!important;border-color:currentColor}.katex .katex-version:after{content:"0.16.45"}.katex .katex-mathml{clip:rect(1px,1px,1px,1px);border:0;height:1px;overflow:hidden;padding:0;position:absolute;width:1px}.katex .katex-html>.newline{display:block}.katex .base{position:relative;white-space:nowrap;width:-webkit-min-content;width:-moz-min-content;width:min-content}.katex .base,.katex .strut{display:inline-block}.katex .textbf{font-weight:700}.katex .textit{font-style:italic}.katex .textrm{font-family:KaTeX_Main}.katex .textsf{font-family:KaTeX_SansSerif}.katex .texttt{font-family:KaTeX_Typewriter}.katex .mathnormal{font-family:KaTeX_Math;font-style:italic}.katex .mathit{font-family:KaTeX_Main;font-style:italic}.katex .mathrm{font-style:normal}.katex .mathbf{font-family:KaTeX_Main;font-weight:700}.katex .boldsymbol{font-family:KaTeX_Math;font-style:italic;font-weight:700}.katex .amsrm,.katex .mathbb,.katex .textbb{font-family:KaTeX_AMS}.katex .mathcal{font-family:KaTeX_Caligraphic}.katex .mathfrak,.katex .textfrak{font-family:KaTeX_Fraktur}.katex .mathboldfrak,.katex .textboldfrak{font-family:KaTeX_Fraktur;font-weight:700}.katex .mathtt{font-family:KaTeX_Typewriter}.katex .mathscr,.katex .textscr{font-family:KaTeX_Script}.katex .mathsf,.katex .textsf{font-family:KaTeX_SansSerif}.katex .mathboldsf,.katex .textboldsf{font-family:KaTeX_SansSerif;font-weight:700}.katex .mathitsf,.katex .mathsfit,.katex .textitsf{font-family:KaTeX_SansSerif;font-style:italic}.katex .mainrm{font-family:KaTeX_Main;font-style:normal}.katex .vlist-t{border-collapse:collapse;display:inline-table;table-layout:fixed}.katex .vlist-r{display:table-row}.katex .vlist{display:table-cell;position:relative;vertical-align:bottom}.katex .vlist>span{display:block;height:0;position:relative}.katex .vlist>span>span{display:inline-block}.katex .vlist>span>.pstrut{overflow:hidden;width:0}.katex .vlist-t2{margin-right:-2px}.katex .vlist-s{display:table-cell;font-size:1px;min-width:2px;vertical-align:bottom;width:2px}.katex .vbox{align-items:baseline;display:inline-flex;flex-direction:column}.katex .hbox{width:100%}.katex .hbox,.katex .thinbox{display:inline-flex;flex-direction:row}.katex .thinbox{max-width:0;width:0}.katex .msupsub{text-align:left}.katex .mfrac>span>span{text-align:center}.katex .mfrac .frac-line{border-bottom-style:solid;display:inline-block;width:100%}.katex .hdashline,.katex .hline,.katex .mfrac .frac-line,.katex .overline .overline-line,.katex .rule,.katex .underline .underline-line{min-height:1px}.katex .mspace{display:inline-block}.katex .smash{display:inline;line-height:0}.katex .clap,.katex .llap,.katex .rlap{position:relative;width:0}.katex .clap>.inner,.katex .llap>.inner,.katex .rlap>.inner{position:absolute}.katex .clap>.fix,.katex .llap>.fix,.katex .rlap>.fix{display:inline-block}.katex .llap>.inner{right:0}.katex .clap>.inner,.katex .rlap>.inner{left:0}.katex .clap>.inner>span{margin-left:-50%;margin-right:50%}.katex .rule{border:0 solid;display:inline-block;position:relative}.katex .hline,.katex .overline .overline-line,.katex .underline .underline-line{border-bottom-style:solid;display:inline-block;width:100%}.katex .hdashline{border-bottom-style:dashed;display:inline-block;width:100%}.katex .sqrt>.root{margin-left:.2777777778em;margin-right:-.5555555556em}.katex .fontsize-ensurer.reset-size1.size1,.katex .sizing.reset-size1.size1{font-size:1em}.katex .fontsize-ensurer.reset-size1.size2,.katex .sizing.reset-size1.size2{font-size:1.2em}.katex .fontsize-ensurer.reset-size1.size3,.katex .sizing.reset-size1.size3{font-size:1.4em}.katex .fontsize-ensurer.reset-size1.size4,.katex .sizing.reset-size1.size4{font-size:1.6em}.katex .fontsize-ensurer.reset-size1.size5,.katex .sizing.reset-size1.size5{font-size:1.8em}.katex .fontsize-ensurer.reset-size1.size6,.katex .sizing.reset-size1.size6{font-size:2em}.katex .fontsize-ensurer.reset-size1.size7,.katex .sizing.reset-size1.size7{font-size:2.4em}.katex .fontsize-ensurer.reset-size1.size8,.katex .sizing.reset-size1.size8{font-size:2.88em}.katex .fontsize-ensurer.reset-size1.size9,.katex .sizing.reset-size1.size9{font-size:3.456em}.katex .fontsize-ensurer.reset-size1.size10,.katex .sizing.reset-size1.size10{font-size:4.148em}.katex .fontsize-ensurer.reset-size1.size11,.katex .sizing.reset-size1.size11{font-size:4.976em}.katex .fontsize-ensurer.reset-size2.size1,.katex .sizing.reset-size2.size1{font-size:.8333333333em}.katex .fontsize-ensurer.reset-size2.size2,.katex .sizing.reset-size2.size2{font-size:1em}.katex .fontsize-ensurer.reset-size2.size3,.katex .sizing.reset-size2.size3{font-size:1.1666666667em}.katex .fontsize-ensurer.reset-size2.size4,.katex .sizing.reset-size2.size4{font-size:1.3333333333em}.katex .fontsize-ensurer.reset-size2.size5,.katex .sizing.reset-size2.size5{font-size:1.5em}.katex .fontsize-ensurer.reset-size2.size6,.katex .sizing.reset-size2.size6{font-size:1.6666666667em}.katex .fontsize-ensurer.reset-size2.size7,.katex .sizing.reset-size2.size7{font-size:2em}.katex .fontsize-ensurer.reset-size2.size8,.katex .sizing.reset-size2.size8{font-size:2.4em}.katex .fontsize-ensurer.reset-size2.size9,.katex .sizing.reset-size2.size9{font-size:2.88em}.katex .fontsize-ensurer.reset-size2.size10,.katex .sizing.reset-size2.size10{font-size:3.4566666667em}.katex .fontsize-ensurer.reset-size2.size11,.katex .sizing.reset-size2.size11{font-size:4.1466666667em}.katex .fontsize-ensurer.reset-size3.size1,.katex .sizing.reset-size3.size1{font-size:.7142857143em}.katex .fontsize-ensurer.reset-size3.size2,.katex .sizing.reset-size3.size2{font-size:.8571428571em}.katex .fontsize-ensurer.reset-size3.size3,.katex .sizing.reset-size3.size3{font-size:1em}.katex .fontsize-ensurer.reset-size3.size4,.katex .sizing.reset-size3.size4{font-size:1.1428571429em}.katex .fontsize-ensurer.reset-size3.size5,.katex .sizing.reset-size3.size5{font-size:1.2857142857em}.katex .fontsize-ensurer.reset-size3.size6,.katex .sizing.reset-size3.size6{font-size:1.4285714286em}.katex .fontsize-ensurer.reset-size3.size7,.katex .sizing.reset-size3.size7{font-size:1.7142857143em}.katex .fontsize-ensurer.reset-size3.size8,.katex .sizing.reset-size3.size8{font-size:2.0571428571em}.katex .fontsize-ensurer.reset-size3.size9,.katex .sizing.reset-size3.size9{font-size:2.4685714286em}.katex .fontsize-ensurer.reset-size3.size10,.katex .sizing.reset-size3.size10{font-size:2.9628571429em}.katex .fontsize-ensurer.reset-size3.size11,.katex .sizing.reset-size3.size11{font-size:3.5542857143em}.katex .fontsize-ensurer.reset-size4.size1,.katex .sizing.reset-size4.size1{font-size:.625em}.katex .fontsize-ensurer.reset-size4.size2,.katex .sizing.reset-size4.size2{font-size:.75em}.katex .fontsize-ensurer.reset-size4.size3,.katex .sizing.reset-size4.size3{font-size:.875em}.katex .fontsize-ensurer.reset-size4.size4,.katex .sizing.reset-size4.size4{font-size:1em}.katex .fontsize-ensurer.reset-size4.size5,.katex .sizing.reset-size4.size5{font-size:1.125em}.katex .fontsize-ensurer.reset-size4.size6,.katex .sizing.reset-size4.size6{font-size:1.25em}.katex .fontsize-ensurer.reset-size4.size7,.katex .sizing.reset-size4.size7{font-size:1.5em}.katex .fontsize-ensurer.reset-size4.size8,.katex .sizing.reset-size4.size8{font-size:1.8em}.katex .fontsize-ensurer.reset-size4.size9,.katex .sizing.reset-size4.size9{font-size:2.16em}.katex .fontsize-ensurer.reset-size4.size10,.katex .sizing.reset-size4.size10{font-size:2.5925em}.katex .fontsize-ensurer.reset-size4.size11,.katex .sizing.reset-size4.size11{font-size:3.11em}.katex .fontsize-ensurer.reset-size5.size1,.katex .sizing.reset-size5.size1{font-size:.5555555556em}.katex .fontsize-ensurer.reset-size5.size2,.katex .sizing.reset-size5.size2{font-size:.6666666667em}.katex .fontsize-ensurer.reset-size5.size3,.katex .sizing.reset-size5.size3{font-size:.7777777778em}.katex .fontsize-ensurer.reset-size5.size4,.katex .sizing.reset-size5.size4{font-size:.8888888889em}.katex .fontsize-ensurer.reset-size5.size5,.katex .sizing.reset-size5.size5{font-size:1em}.katex .fontsize-ensurer.reset-size5.size6,.katex .sizing.reset-size5.size6{font-size:1.1111111111em}.katex .fontsize-ensurer.reset-size5.size7,.katex .sizing.reset-size5.size7{font-size:1.3333333333em}.katex .fontsize-ensurer.reset-size5.size8,.katex .sizing.reset-size5.size8{font-size:1.6em}.katex .fontsize-ensurer.reset-size5.size9,.katex .sizing.reset-size5.size9{font-size:1.92em}.katex .fontsize-ensurer.reset-size5.size10,.katex .sizing.reset-size5.size10{font-size:2.3044444444em}.katex .fontsize-ensurer.reset-size5.size11,.katex .sizing.reset-size5.size11{font-size:2.7644444444em}.katex .fontsize-ensurer.reset-size6.size1,.katex .sizing.reset-size6.size1{font-size:.5em}.katex .fontsize-ensurer.reset-size6.size2,.katex .sizing.reset-size6.size2{font-size:.6em}.katex .fontsize-ensurer.reset-size6.size3,.katex .sizing.reset-size6.size3{font-size:.7em}.katex .fontsize-ensurer.reset-size6.size4,.katex .sizing.reset-size6.size4{font-size:.8em}.katex .fontsize-ensurer.reset-size6.size5,.katex .sizing.reset-size6.size5{font-size:.9em}.katex .fontsize-ensurer.reset-size6.size6,.katex .sizing.reset-size6.size6{font-size:1em}.katex .fontsize-ensurer.reset-size6.size7,.katex .sizing.reset-size6.size7{font-size:1.2em}.katex .fontsize-ensurer.reset-size6.size8,.katex .sizing.reset-size6.size8{font-size:1.44em}.katex .fontsize-ensurer.reset-size6.size9,.katex .sizing.reset-size6.size9{font-size:1.728em}.katex .fontsize-ensurer.reset-size6.size10,.katex .sizing.reset-size6.size10{font-size:2.074em}.katex .fontsize-ensurer.reset-size6.size11,.katex .sizing.reset-size6.size11{font-size:2.488em}.katex .fontsize-ensurer.reset-size7.size1,.katex .sizing.reset-size7.size1{font-size:.4166666667em}.katex .fontsize-ensurer.reset-size7.size2,.katex .sizing.reset-size7.size2{font-size:.5em}.katex .fontsize-ensurer.reset-size7.size3,.katex .sizing.reset-size7.size3{font-size:.5833333333em}.katex .fontsize-ensurer.reset-size7.size4,.katex .sizing.reset-size7.size4{font-size:.6666666667em}.katex .fontsize-ensurer.reset-size7.size5,.katex .sizing.reset-size7.size5{font-size:.75em}.katex .fontsize-ensurer.reset-size7.size6,.katex .sizing.reset-size7.size6{font-size:.8333333333em}.katex .fontsize-ensurer.reset-size7.size7,.katex .sizing.reset-size7.size7{font-size:1em}.katex .fontsize-ensurer.reset-size7.size8,.katex .sizing.reset-size7.size8{font-size:1.2em}.katex .fontsize-ensurer.reset-size7.size9,.katex .sizing.reset-size7.size9{font-size:1.44em}.katex .fontsize-ensurer.reset-size7.size10,.katex .sizing.reset-size7.size10{font-size:1.7283333333em}.katex .fontsize-ensurer.reset-size7.size11,.katex .sizing.reset-size7.size11{font-size:2.0733333333em}.katex .fontsize-ensurer.reset-size8.size1,.katex .sizing.reset-size8.size1{font-size:.3472222222em}.katex .fontsize-ensurer.reset-size8.size2,.katex .sizing.reset-size8.size2{font-size:.4166666667em}.katex .fontsize-ensurer.reset-size8.size3,.katex .sizing.reset-size8.size3{font-size:.4861111111em}.katex .fontsize-ensurer.reset-size8.size4,.katex .sizing.reset-size8.size4{font-size:.5555555556em}.katex .fontsize-ensurer.reset-size8.size5,.katex .sizing.reset-size8.size5{font-size:.625em}.katex .fontsize-ensurer.reset-size8.size6,.katex .sizing.reset-size8.size6{font-size:.6944444444em}.katex .fontsize-ensurer.reset-size8.size7,.katex .sizing.reset-size8.size7{font-size:.8333333333em}.katex .fontsize-ensurer.reset-size8.size8,.katex .sizing.reset-size8.size8{font-size:1em}.katex .fontsize-ensurer.reset-size8.size9,.katex .sizing.reset-size8.size9{font-size:1.2em}.katex .fontsize-ensurer.reset-size8.size10,.katex .sizing.reset-size8.size10{font-size:1.4402777778em}.katex .fontsize-ensurer.reset-size8.size11,.katex .sizing.reset-size8.size11{font-size:1.7277777778em}.katex .fontsize-ensurer.reset-size9.size1,.katex .sizing.reset-size9.size1{font-size:.2893518519em}.katex .fontsize-ensurer.reset-size9.size2,.katex .sizing.reset-size9.size2{font-size:.3472222222em}.katex .fontsize-ensurer.reset-size9.size3,.katex .sizing.reset-size9.size3{font-size:.4050925926em}.katex .fontsize-ensurer.reset-size9.size4,.katex .sizing.reset-size9.size4{font-size:.462962963em}.katex .fontsize-ensurer.reset-size9.size5,.katex .sizing.reset-size9.size5{font-size:.5208333333em}.katex .fontsize-ensurer.reset-size9.size6,.katex .sizing.reset-size9.size6{font-size:.5787037037em}.katex .fontsize-ensurer.reset-size9.size7,.katex .sizing.reset-size9.size7{font-size:.6944444444em}.katex .fontsize-ensurer.reset-size9.size8,.katex .sizing.reset-size9.size8{font-size:.8333333333em}.katex .fontsize-ensurer.reset-size9.size9,.katex .sizing.reset-size9.size9{font-size:1em}.katex .fontsize-ensurer.reset-size9.size10,.katex .sizing.reset-size9.size10{font-size:1.2002314815em}.katex .fontsize-ensurer.reset-size9.size11,.katex .sizing.reset-size9.size11{font-size:1.4398148148em}.katex .fontsize-ensurer.reset-size10.size1,.katex .sizing.reset-size10.size1{font-size:.2410800386em}.katex .fontsize-ensurer.reset-size10.size2,.katex .sizing.reset-size10.size2{font-size:.2892960463em}.katex .fontsize-ensurer.reset-size10.size3,.katex .sizing.reset-size10.size3{font-size:.337512054em}.katex .fontsize-ensurer.reset-size10.size4,.katex .sizing.reset-size10.size4{font-size:.3857280617em}.katex .fontsize-ensurer.reset-size10.size5,.katex .sizing.reset-size10.size5{font-size:.4339440694em}.katex .fontsize-ensurer.reset-size10.size6,.katex .sizing.reset-size10.size6{font-size:.4821600771em}.katex .fontsize-ensurer.reset-size10.size7,.katex .sizing.reset-size10.size7{font-size:.5785920926em}.katex .fontsize-ensurer.reset-size10.size8,.katex .sizing.reset-size10.size8{font-size:.6943105111em}.katex .fontsize-ensurer.reset-size10.size9,.katex .sizing.reset-size10.size9{font-size:.8331726133em}.katex .fontsize-ensurer.reset-size10.size10,.katex .sizing.reset-size10.size10{font-size:1em}.katex .fontsize-ensurer.reset-size10.size11,.katex .sizing.reset-size10.size11{font-size:1.1996142719em}.katex .fontsize-ensurer.reset-size11.size1,.katex .sizing.reset-size11.size1{font-size:.2009646302em}.katex .fontsize-ensurer.reset-size11.size2,.katex .sizing.reset-size11.size2{font-size:.2411575563em}.katex .fontsize-ensurer.reset-size11.size3,.katex .sizing.reset-size11.size3{font-size:.2813504823em}.katex .fontsize-ensurer.reset-size11.size4,.katex .sizing.reset-size11.size4{font-size:.3215434084em}.katex .fontsize-ensurer.reset-size11.size5,.katex .sizing.reset-size11.size5{font-size:.3617363344em}.katex .fontsize-ensurer.reset-size11.size6,.katex .sizing.reset-size11.size6{font-size:.4019292605em}.katex .fontsize-ensurer.reset-size11.size7,.katex .sizing.reset-size11.size7{font-size:.4823151125em}.katex .fontsize-ensurer.reset-size11.size8,.katex .sizing.reset-size11.size8{font-size:.578778135em}.katex .fontsize-ensurer.reset-size11.size9,.katex .sizing.reset-size11.size9{font-size:.6945337621em}.katex .fontsize-ensurer.reset-size11.size10,.katex .sizing.reset-size11.size10{font-size:.8336012862em}.katex .fontsize-ensurer.reset-size11.size11,.katex .sizing.reset-size11.size11{font-size:1em}.katex .delimsizing.size1{font-family:KaTeX_Size1}.katex .delimsizing.size2{font-family:KaTeX_Size2}.katex .delimsizing.size3{font-family:KaTeX_Size3}.katex .delimsizing.size4{font-family:KaTeX_Size4}.katex .delimsizing.mult .delim-size1>span{font-family:KaTeX_Size1}.katex .delimsizing.mult .delim-size4>span{font-family:KaTeX_Size4}.katex .nulldelimiter{display:inline-block;width:.12em}.katex .delimcenter,.katex .op-symbol{position:relative}.katex .op-symbol.small-op{font-family:KaTeX_Size1}.katex .op-symbol.large-op{font-family:KaTeX_Size2}.katex .accent>.vlist-t,.katex .op-limits>.vlist-t{text-align:center}.katex .accent .accent-body{position:relative}.katex .accent .accent-body:not(.accent-full){width:0}.katex .overlay{display:block}.katex .mtable .vertical-separator{display:inline-block;min-width:1px}.katex .mtable .arraycolsep{display:inline-block}.katex .mtable .col-align-c>.vlist-t{text-align:center}.katex .mtable .col-align-l>.vlist-t{text-align:left}.katex .mtable .col-align-r>.vlist-t{text-align:right}.katex .svg-align{text-align:left}.katex svg{fill:currentColor;stroke:currentColor;display:block;height:inherit;position:absolute;width:100%}.katex svg path{stroke:none}.katex svg{fill-rule:nonzero;fill-opacity:1;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1}.katex img{border-style:none;max-height:none;max-width:none;min-height:0;min-width:0}.katex .stretchy{display:block;overflow:hidden;position:relative;width:100%}.katex .stretchy:after,.katex .stretchy:before{content:""}.katex .hide-tail{overflow:hidden;position:relative;width:100%}.katex .halfarrow-left{left:0;overflow:hidden;position:absolute;width:50.2%}.katex .halfarrow-right{overflow:hidden;position:absolute;right:0;width:50.2%}.katex .brace-left{left:0;overflow:hidden;position:absolute;width:25.1%}.katex .brace-center{left:25%;overflow:hidden;position:absolute;width:50%}.katex .brace-right{overflow:hidden;position:absolute;right:0;width:25.1%}.katex .x-arrow-pad{padding:0 .5em}.katex .cd-arrow-pad{padding:0 .55556em 0 .27778em}.katex .mover,.katex .munder,.katex .x-arrow{text-align:center}.katex .boxpad{padding:0 .3em}.katex .fbox,.katex .fcolorbox{border:.04em solid;box-sizing:border-box}.katex .cancel-pad{padding:0 .2em}.katex .cancel-lap{margin-left:-.2em;margin-right:-.2em}.katex .sout{border-bottom-style:solid;border-bottom-width:.08em}.katex .angl{border-right:.049em solid;border-top:.049em solid;box-sizing:border-box;margin-right:.03889em}.katex .anglpad{padding:0 .03889em}.katex .eqn-num:before{content:"(" counter(katexEqnNo) ")";counter-increment:katexEqnNo}.katex .mml-eqn-num:before{content:"(" counter(mmlEqnNo) ")";counter-increment:mmlEqnNo}.katex .mtr-glue{width:50%}.katex .cd-vert-arrow{display:inline-block;position:relative}.katex .cd-label-left{display:inline-block;position:absolute;right:calc(50% + .3em);text-align:left}.katex .cd-label-right{display:inline-block;left:calc(50% + .3em);position:absolute;text-align:right}.katex-display{display:block;margin:1em 0;text-align:center}.katex-display>.katex{display:block;text-align:center;white-space:nowrap}.katex-display>.katex>.katex-html{display:block;position:relative}.katex-display>.katex>.katex-html>.tag{position:absolute;right:0}.katex-display.leqno>.katex>.katex-html>.tag{left:0;right:auto}.katex-display.fleqn>.katex{padding-left:2em;text-align:left}body{counter-reset:katexEqnNo mmlEqnNo} diff --git a/index.html b/index.html index b0c4b3666032a737f3903db53e6a8a9272483e28..62037b6e2457d9e1679d2157a759040b358dde3c 100644 --- a/index.html +++ b/index.html @@ -1,19 +1,17 @@ - - - - - - My static Space - - - -
-

Welcome to your static Space!

-

You can modify this app directly by editing index.html in the Files and versions tab.

-

- Also don't forget to check the - Spaces documentation. -

-
- + + + + + + neuron-runner + + + + +
+
+
+ +
+