diff --git a/TrackingToolWeb/.vscode/settings.json b/TrackingToolWeb/.vscode/settings.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/TrackingToolWeb/.vscode/settings.json @@ -0,0 +1 @@ +{} diff --git a/TrackingToolWeb/static/assets/index-B9NPk65I.css b/TrackingToolWeb/static/assets/index-B9NPk65I.css new file mode 100644 index 0000000..9da065c --- /dev/null +++ b/TrackingToolWeb/static/assets/index-B9NPk65I.css @@ -0,0 +1 @@ +@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-400:oklch(70.4% .191 22.216);--color-red-600:oklch(57.7% .245 27.325);--color-green-600:oklch(62.7% .194 149.214);--color-green-700:oklch(52.7% .154 150.069);--color-emerald-300:oklch(84.5% .143 164.978);--color-emerald-400:oklch(76.5% .177 163.223);--color-blue-50:oklch(97% .014 254.604);--color-blue-200:oklch(88.2% .059 254.128);--color-blue-500:oklch(62.3% .214 259.815);--color-blue-600:oklch(54.6% .245 262.881);--color-blue-700:oklch(48.8% .243 264.376);--color-blue-950:oklch(28.2% .091 267.935);--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--color-gray-200:oklch(92.8% .006 264.531);--color-gray-400:oklch(70.7% .022 261.325);--color-gray-600:oklch(44.6% .03 256.802);--color-gray-900:oklch(21% .034 264.665);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-md:28rem;--container-lg:32rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75/1.125);--text-8xl:6rem;--text-8xl--line-height:1;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-widest:.1em;--radius-xs:.125rem;--ease-in-out:cubic-bezier(.4,0,.2,1);--animate-spin:spin 1s linear infinite;--animate-pulse:pulse 2s cubic-bezier(.4,0,.6,1)infinite;--blur-sm:8px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}*{border-color:var(--border);outline-color:var(--ring)}@supports (color:color-mix(in lab,red,red)){*{outline-color:color-mix(in oklab,var(--ring)50%,transparent)}}body{background-color:var(--background);color:var(--foreground)}}@layer components;@layer utilities{.\@container\/card-header{container:card-header/inline-size}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.inset-0{inset:calc(var(--spacing)*0)}.-top-3{top:calc(var(--spacing)*-3)}.top-0{top:calc(var(--spacing)*0)}.top-1\/2{top:50%}.top-4{top:calc(var(--spacing)*4)}.top-\[50\%\]{top:50%}.right-0{right:calc(var(--spacing)*0)}.right-4{right:calc(var(--spacing)*4)}.bottom-10{bottom:calc(var(--spacing)*10)}.left-0{left:calc(var(--spacing)*0)}.left-2{left:calc(var(--spacing)*2)}.left-4{left:calc(var(--spacing)*4)}.left-\[50\%\]{left:50%}.z-10{z-index:10}.z-40{z-index:40}.z-50{z-index:50}.col-start-2{grid-column-start:2}.row-span-2{grid-row:span 2/span 2}.row-start-1{grid-row-start:1}.-mx-1{margin-inline:calc(var(--spacing)*-1)}.my-1{margin-block:calc(var(--spacing)*1)}.mt-4{margin-top:calc(var(--spacing)*4)}.mr-2{margin-right:calc(var(--spacing)*2)}.mr-96{margin-right:calc(var(--spacing)*96)}.mb-1{margin-bottom:calc(var(--spacing)*1)}.mb-3{margin-bottom:calc(var(--spacing)*3)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.ml-96{margin-left:calc(var(--spacing)*96)}.ml-auto{margin-left:auto}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline-flex{display:inline-flex}.aspect-square{aspect-ratio:1}.size-2{width:calc(var(--spacing)*2);height:calc(var(--spacing)*2)}.size-3\.5{width:calc(var(--spacing)*3.5);height:calc(var(--spacing)*3.5)}.size-4{width:calc(var(--spacing)*4);height:calc(var(--spacing)*4)}.size-8{width:calc(var(--spacing)*8);height:calc(var(--spacing)*8)}.size-9{width:calc(var(--spacing)*9);height:calc(var(--spacing)*9)}.size-10{width:calc(var(--spacing)*10);height:calc(var(--spacing)*10)}.size-12{width:calc(var(--spacing)*12);height:calc(var(--spacing)*12)}.size-16{width:calc(var(--spacing)*16);height:calc(var(--spacing)*16)}.size-full{width:100%;height:100%}.h-1\.5{height:calc(var(--spacing)*1.5)}.h-2\.5{height:calc(var(--spacing)*2.5)}.h-4{height:calc(var(--spacing)*4)}.h-6{height:calc(var(--spacing)*6)}.h-8{height:calc(var(--spacing)*8)}.h-9{height:calc(var(--spacing)*9)}.h-10{height:calc(var(--spacing)*10)}.h-40{height:calc(var(--spacing)*40)}.h-\[90vh\]{height:90vh}.h-\[calc\(100\%-1px\)\]{height:calc(100% - 1px)}.h-full{height:100%}.h-px{height:1px}.h-screen{height:100vh}.max-h-\(--radix-dropdown-menu-content-available-height\){max-height:var(--radix-dropdown-menu-content-available-height)}.min-h-screen{min-height:100vh}.w-2\.5{width:calc(var(--spacing)*2.5)}.w-4{width:calc(var(--spacing)*4)}.w-6{width:calc(var(--spacing)*6)}.w-8{width:calc(var(--spacing)*8)}.w-40{width:calc(var(--spacing)*40)}.w-48{width:calc(var(--spacing)*48)}.w-96{width:calc(var(--spacing)*96)}.w-fit{width:fit-content}.w-full{width:100%}.max-w-\[calc\(100\%-2rem\)\]{max-width:calc(100% - 2rem)}.min-w-0{min-width:calc(var(--spacing)*0)}.min-w-32{min-width:calc(var(--spacing)*32)}.min-w-\[8rem\]{min-width:8rem}.flex-1{flex:1}.shrink-0{flex-shrink:0}.origin-\(--radix-dropdown-menu-content-transform-origin\){transform-origin:var(--radix-dropdown-menu-content-transform-origin)}.-translate-x-full{--tw-translate-x:-100%;translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-x-0{--tw-translate-x:calc(var(--spacing)*0);translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-x-\[-50\%\]{--tw-translate-x:-50%;translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-x-full{--tw-translate-x:100%;translate:var(--tw-translate-x)var(--tw-translate-y)}.-translate-y-1\/2{--tw-translate-y: -50% ;translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-y-\[-50\%\]{--tw-translate-y:-50%;translate:var(--tw-translate-x)var(--tw-translate-y)}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.auto-rows-min{grid-auto-rows:min-content}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-rows-\[auto_auto\]{grid-template-rows:auto auto}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-1{gap:calc(var(--spacing)*1)}.gap-1\.5{gap:calc(var(--spacing)*1.5)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}.gap-6{gap:calc(var(--spacing)*6)}.gap-8{gap:calc(var(--spacing)*8)}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*2)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*2)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*3)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*3)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*4)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*4)*calc(1 - var(--tw-space-y-reverse)))}.self-start{align-self:flex-start}.justify-self-end{justify-self:flex-end}.overflow-hidden{overflow:hidden}.overflow-x-hidden{overflow-x:hidden}.overflow-y-auto{overflow-y:auto}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:calc(var(--radius) + 4px)}.rounded-xs{border-radius:var(--radius-xs)}.rounded-tl-md{border-top-left-radius:calc(var(--radius) - 2px)}.rounded-tr-md{border-top-right-radius:calc(var(--radius) - 2px)}.rounded-br-md{border-bottom-right-radius:calc(var(--radius) - 2px)}.rounded-bl-md{border-bottom-left-radius:calc(var(--radius) - 2px)}.border{border-style:var(--tw-border-style);border-width:1px}.border-4{border-style:var(--tw-border-style);border-width:4px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-t-\[3px\]{border-top-style:var(--tw-border-style);border-top-width:3px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-r-\[3px\]{border-right-style:var(--tw-border-style);border-right-width:3px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-\[3px\]{border-bottom-style:var(--tw-border-style);border-bottom-width:3px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-\[3px\]{border-left-style:var(--tw-border-style);border-left-width:3px}.border-blue-200{border-color:var(--color-blue-200)}.border-blue-500{border-color:var(--color-blue-500)}.border-blue-500\/30{border-color:#3080ff4d}@supports (color:color-mix(in lab,red,red)){.border-blue-500\/30{border-color:color-mix(in oklab,var(--color-blue-500)30%,transparent)}}.border-emerald-400\/90{border-color:#00d294e6}@supports (color:color-mix(in lab,red,red)){.border-emerald-400\/90{border-color:color-mix(in oklab,var(--color-emerald-400)90%,transparent)}}.border-gray-200{border-color:var(--color-gray-200)}.border-input{border-color:var(--input)}.border-transparent{border-color:#0000}.border-t-transparent{border-top-color:#0000}.border-l-transparent{border-left-color:#0000}.bg-background{background-color:var(--background)}.bg-black{background-color:var(--color-black)}.bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab,red,red)){.bg-black\/50{background-color:color-mix(in oklab,var(--color-black)50%,transparent)}}.bg-blue-50{background-color:var(--color-blue-50)}.bg-blue-600{background-color:var(--color-blue-600)}.bg-border{background-color:var(--border)}.bg-card{background-color:var(--card)}.bg-destructive{background-color:var(--destructive)}.bg-emerald-300{background-color:var(--color-emerald-300)}.bg-emerald-400{background-color:var(--color-emerald-400)}.bg-gray-50{background-color:var(--color-gray-50)}.bg-green-600{background-color:var(--color-green-600)}.bg-muted{background-color:var(--muted)}.bg-popover{background-color:var(--popover)}.bg-primary{background-color:var(--primary)}.bg-secondary{background-color:var(--secondary)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.bg-white\/25{background-color:#ffffff40}@supports (color:color-mix(in lab,red,red)){.bg-white\/25{background-color:color-mix(in oklab,var(--color-white)25%,transparent)}}.bg-white\/90{background-color:#ffffffe6}@supports (color:color-mix(in lab,red,red)){.bg-white\/90{background-color:color-mix(in oklab,var(--color-white)90%,transparent)}}.bg-white\/95{background-color:#fffffff2}@supports (color:color-mix(in lab,red,red)){.bg-white\/95{background-color:color-mix(in oklab,var(--color-white)95%,transparent)}}.fill-current{fill:currentColor}.object-cover{object-fit:cover}.p-1{padding:calc(var(--spacing)*1)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.p-6{padding:calc(var(--spacing)*6)}.p-\[3px\]{padding:3px}.p-px{padding:1px}.px-2{padding-inline:calc(var(--spacing)*2)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.px-6{padding-inline:calc(var(--spacing)*6)}.px-8{padding-inline:calc(var(--spacing)*8)}.py-0\.5{padding-block:calc(var(--spacing)*.5)}.py-1{padding-block:calc(var(--spacing)*1)}.py-1\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-6{padding-block:calc(var(--spacing)*6)}.pt-2{padding-top:calc(var(--spacing)*2)}.pt-4{padding-top:calc(var(--spacing)*4)}.pr-2{padding-right:calc(var(--spacing)*2)}.pl-8{padding-left:calc(var(--spacing)*8)}.text-center{text-align:center}.text-8xl{font-size:var(--text-8xl);line-height:var(--tw-leading,var(--text-8xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.leading-none{--tw-leading:1;line-height:1}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-widest{--tw-tracking:var(--tracking-widest);letter-spacing:var(--tracking-widest)}.whitespace-nowrap{white-space:nowrap}.text-blue-600{color:var(--color-blue-600)}.text-card-foreground{color:var(--card-foreground)}.text-destructive{color:var(--destructive)}.text-foreground{color:var(--foreground)}.text-gray-400{color:var(--color-gray-400)}.text-gray-600{color:var(--color-gray-600)}.text-gray-900{color:var(--color-gray-900)}.text-green-600{color:var(--color-green-600)}.text-muted-foreground{color:var(--muted-foreground)}.text-popover-foreground{color:var(--popover-foreground)}.text-primary{color:var(--primary)}.text-primary-foreground{color:var(--primary-foreground)}.text-red-600{color:var(--color-red-600)}.text-secondary-foreground{color:var(--secondary-foreground)}.text-white{color:var(--color-white)}.capitalize{text-transform:capitalize}.underline-offset-4{text-underline-offset:4px}.opacity-70{opacity:.7}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\[0_0_12px_rgba\(110\,231\,183\,0\.9\)\]{--tw-shadow:0 0 12px var(--tw-shadow-color,#6ee7b7e6);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-md{--tw-shadow:0 4px 6px -1px var(--tw-shadow-color,#0000001a),0 2px 4px -2px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a),0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xs{--tw-shadow:0 1px 2px 0 var(--tw-shadow-color,#0000000d);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-offset-background{--tw-ring-offset-color:var(--background)}.outline-hidden{--tw-outline-style:none;outline-style:none}@media(forced-colors:active){.outline-hidden{outline-offset:2px;outline:2px solid #0000}}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[color\,box-shadow\]{transition-property:color,box-shadow;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-150{--tw-duration:.15s;transition-duration:.15s}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.will-change-transform{will-change:transform}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.running{animation-play-state:running}.zoom-out{--tw-exit-scale:0}.group-data-\[disabled\=true\]\:pointer-events-none:is(:where(.group)[data-disabled=true] *){pointer-events:none}.group-data-\[disabled\=true\]\:opacity-50:is(:where(.group)[data-disabled=true] *){opacity:.5}.peer-disabled\:cursor-not-allowed:is(:where(.peer):disabled~*){cursor:not-allowed}.peer-disabled\:opacity-50:is(:where(.peer):disabled~*){opacity:.5}.selection\:bg-primary ::selection{background-color:var(--primary)}.selection\:bg-primary::selection{background-color:var(--primary)}.selection\:text-primary-foreground ::selection{color:var(--primary-foreground)}.selection\:text-primary-foreground::selection{color:var(--primary-foreground)}.file\:inline-flex::file-selector-button{display:inline-flex}.file\:h-7::file-selector-button{height:calc(var(--spacing)*7)}.file\:border-0::file-selector-button{border-style:var(--tw-border-style);border-width:0}.file\:bg-transparent::file-selector-button{background-color:#0000}.file\:text-sm::file-selector-button{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.file\:font-medium::file-selector-button{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.file\:text-foreground::file-selector-button{color:var(--foreground)}.placeholder\:text-muted-foreground::placeholder{color:var(--muted-foreground)}@media(hover:hover){.hover\:scale-\[1\.01\]:hover{scale:1.01}.hover\:bg-accent:hover{background-color:var(--accent)}.hover\:bg-blue-700:hover{background-color:var(--color-blue-700)}.hover\:bg-destructive\/90:hover{background-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){.hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab,var(--destructive)90%,transparent)}}.hover\:bg-green-700:hover{background-color:var(--color-green-700)}.hover\:bg-primary\/90:hover{background-color:var(--primary)}@supports (color:color-mix(in lab,red,red)){.hover\:bg-primary\/90:hover{background-color:color-mix(in oklab,var(--primary)90%,transparent)}}.hover\:bg-secondary\/80:hover{background-color:var(--secondary)}@supports (color:color-mix(in lab,red,red)){.hover\:bg-secondary\/80:hover{background-color:color-mix(in oklab,var(--secondary)80%,transparent)}}.hover\:bg-white:hover{background-color:var(--color-white)}.hover\:text-accent-foreground:hover{color:var(--accent-foreground)}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.hover\:shadow-md:hover{--tw-shadow:0 4px 6px -1px var(--tw-shadow-color,#0000001a),0 2px 4px -2px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}.focus\:bg-accent:focus{background-color:var(--accent)}.focus\:text-accent-foreground:focus{color:var(--accent-foreground)}.focus\:text-red-600:focus{color:var(--color-red-600)}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(2px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-ring:focus{--tw-ring-color:var(--ring)}.focus\:ring-offset-2:focus{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,)0 0 0 var(--tw-ring-offset-width)var(--tw-ring-offset-color)}.focus\:outline-hidden:focus{--tw-outline-style:none;outline-style:none}@media(forced-colors:active){.focus\:outline-hidden:focus{outline-offset:2px;outline:2px solid #0000}}.focus-visible\:border-ring:focus-visible{border-color:var(--ring)}.focus-visible\:ring-\[3px\]:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(3px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-destructive\/20:focus-visible{--tw-ring-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){.focus-visible\:ring-destructive\/20:focus-visible{--tw-ring-color:color-mix(in oklab,var(--destructive)20%,transparent)}}.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color:var(--ring)}@supports (color:color-mix(in lab,red,red)){.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color:color-mix(in oklab,var(--ring)50%,transparent)}}.focus-visible\:outline-1:focus-visible{outline-style:var(--tw-outline-style);outline-width:1px}.focus-visible\:outline-ring:focus-visible{outline-color:var(--ring)}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.has-data-\[slot\=card-action\]\:grid-cols-\[1fr_auto\]:has([data-slot=card-action]){grid-template-columns:1fr auto}.has-\[\>svg\]\:px-2\.5:has(>svg){padding-inline:calc(var(--spacing)*2.5)}.has-\[\>svg\]\:px-3:has(>svg){padding-inline:calc(var(--spacing)*3)}.has-\[\>svg\]\:px-4:has(>svg){padding-inline:calc(var(--spacing)*4)}.aria-invalid\:border-destructive[aria-invalid=true]{border-color:var(--destructive)}.aria-invalid\:ring-destructive\/20[aria-invalid=true]{--tw-ring-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){.aria-invalid\:ring-destructive\/20[aria-invalid=true]{--tw-ring-color:color-mix(in oklab,var(--destructive)20%,transparent)}}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[error\=true\]\:text-destructive[data-error=true]{color:var(--destructive)}.data-\[inset\]\:pl-8[data-inset]{padding-left:calc(var(--spacing)*8)}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y:calc(2*var(--spacing)*-1)}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x:calc(2*var(--spacing))}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x:calc(2*var(--spacing)*-1)}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y:calc(2*var(--spacing))}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:var(--background)}.data-\[state\=active\]\:shadow-sm[data-state=active]{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity:0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale:.95}.data-\[state\=open\]\:animate-in[data-state=open]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:var(--accent)}.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:var(--accent-foreground)}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:var(--muted-foreground)}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity:0}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale:.95}.data-\[variant\=destructive\]\:text-destructive[data-variant=destructive]{color:var(--destructive)}.data-\[variant\=destructive\]\:focus\:bg-destructive\/10[data-variant=destructive]:focus{background-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){.data-\[variant\=destructive\]\:focus\:bg-destructive\/10[data-variant=destructive]:focus{background-color:color-mix(in oklab,var(--destructive)10%,transparent)}}.data-\[variant\=destructive\]\:focus\:text-destructive[data-variant=destructive]:focus{color:var(--destructive)}@media(min-width:40rem){.sm\:max-w-\[425px\]{max-width:425px}.sm\:max-w-lg{max-width:var(--container-lg)}.sm\:max-w-md{max-width:var(--container-md)}.sm\:flex-row{flex-direction:row}.sm\:justify-end{justify-content:flex-end}.sm\:gap-0{gap:calc(var(--spacing)*0)}.sm\:text-left{text-align:left}}@media(min-width:48rem){.md\:text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}}.dark\:border-input:is(.dark *){border-color:var(--input)}.dark\:bg-blue-950:is(.dark *){background-color:var(--color-blue-950)}.dark\:bg-destructive\/60:is(.dark *){background-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){.dark\:bg-destructive\/60:is(.dark *){background-color:color-mix(in oklab,var(--destructive)60%,transparent)}}.dark\:bg-input\/30:is(.dark *){background-color:var(--input)}@supports (color:color-mix(in lab,red,red)){.dark\:bg-input\/30:is(.dark *){background-color:color-mix(in oklab,var(--input)30%,transparent)}}.dark\:text-gray-100:is(.dark *){color:var(--color-gray-100)}.dark\:text-gray-400:is(.dark *){color:var(--color-gray-400)}.dark\:text-muted-foreground:is(.dark *){color:var(--muted-foreground)}.dark\:text-red-400:is(.dark *){color:var(--color-red-400)}@media(hover:hover){.dark\:hover\:bg-accent\/50:is(.dark *):hover{background-color:var(--accent)}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-accent\/50:is(.dark *):hover{background-color:color-mix(in oklab,var(--accent)50%,transparent)}}.dark\:hover\:bg-input\/50:is(.dark *):hover{background-color:var(--input)}@supports (color:color-mix(in lab,red,red)){.dark\:hover\:bg-input\/50:is(.dark *):hover{background-color:color-mix(in oklab,var(--input)50%,transparent)}}}.dark\:focus\:text-red-400:is(.dark *):focus{color:var(--color-red-400)}.dark\:focus-visible\:ring-destructive\/40:is(.dark *):focus-visible{--tw-ring-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){.dark\:focus-visible\:ring-destructive\/40:is(.dark *):focus-visible{--tw-ring-color:color-mix(in oklab,var(--destructive)40%,transparent)}}.dark\:aria-invalid\:ring-destructive\/40:is(.dark *)[aria-invalid=true]{--tw-ring-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){.dark\:aria-invalid\:ring-destructive\/40:is(.dark *)[aria-invalid=true]{--tw-ring-color:color-mix(in oklab,var(--destructive)40%,transparent)}}.dark\:data-\[state\=active\]\:border-input:is(.dark *)[data-state=active]{border-color:var(--input)}.dark\:data-\[state\=active\]\:bg-input\/30:is(.dark *)[data-state=active]{background-color:var(--input)}@supports (color:color-mix(in lab,red,red)){.dark\:data-\[state\=active\]\:bg-input\/30:is(.dark *)[data-state=active]{background-color:color-mix(in oklab,var(--input)30%,transparent)}}.dark\:data-\[state\=active\]\:text-foreground:is(.dark *)[data-state=active]{color:var(--foreground)}.dark\:data-\[variant\=destructive\]\:focus\:bg-destructive\/20:is(.dark *)[data-variant=destructive]:focus{background-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){.dark\:data-\[variant\=destructive\]\:focus\:bg-destructive\/20:is(.dark *)[data-variant=destructive]:focus{background-color:color-mix(in oklab,var(--destructive)20%,transparent)}}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0}.\[\&_svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-4 svg:not([class*=size-]){width:calc(var(--spacing)*4);height:calc(var(--spacing)*4)}.\[\&_svg\:not\(\[class\*\=\'text-\'\]\)\]\:text-muted-foreground svg:not([class*=text-]){color:var(--muted-foreground)}.\[\.border-b\]\:pb-6.border-b{padding-bottom:calc(var(--spacing)*6)}.\[\.border-t\]\:pt-6.border-t{padding-top:calc(var(--spacing)*6)}:is(.data-\[variant\=destructive\]\:\*\:\[svg\]\:\!text-destructive[data-variant=destructive]>*):is(svg){color:var(--destructive)!important}.\[\&\>svg\]\:pointer-events-none>svg{pointer-events:none}.\[\&\>svg\]\:size-3>svg{width:calc(var(--spacing)*3);height:calc(var(--spacing)*3)}@media(hover:hover){a.\[a\&\]\:hover\:bg-accent:hover{background-color:var(--accent)}a.\[a\&\]\:hover\:bg-destructive\/90:hover{background-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){a.\[a\&\]\:hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab,var(--destructive)90%,transparent)}}a.\[a\&\]\:hover\:bg-primary\/90:hover{background-color:var(--primary)}@supports (color:color-mix(in lab,red,red)){a.\[a\&\]\:hover\:bg-primary\/90:hover{background-color:color-mix(in oklab,var(--primary)90%,transparent)}}a.\[a\&\]\:hover\:bg-secondary\/90:hover{background-color:var(--secondary)}@supports (color:color-mix(in lab,red,red)){a.\[a\&\]\:hover\:bg-secondary\/90:hover{background-color:color-mix(in oklab,var(--secondary)90%,transparent)}}a.\[a\&\]\:hover\:text-accent-foreground:hover{color:var(--accent-foreground)}}}@property --tw-animation-delay{syntax:"*";inherits:false;initial-value:0s}@property --tw-animation-direction{syntax:"*";inherits:false;initial-value:normal}@property --tw-animation-duration{syntax:"*";inherits:false}@property --tw-animation-fill-mode{syntax:"*";inherits:false;initial-value:none}@property --tw-animation-iteration-count{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-translate-y{syntax:"*";inherits:false;initial-value:0}:root{--radius:.625rem;--background:oklch(100% 0 0);--foreground:oklch(14.5% 0 0);--card:oklch(100% 0 0);--card-foreground:oklch(14.5% 0 0);--popover:oklch(100% 0 0);--popover-foreground:oklch(14.5% 0 0);--primary:oklch(20.5% 0 0);--primary-foreground:oklch(98.5% 0 0);--secondary:oklch(97% 0 0);--secondary-foreground:oklch(20.5% 0 0);--muted:oklch(97% 0 0);--muted-foreground:oklch(55.6% 0 0);--accent:oklch(97% 0 0);--accent-foreground:oklch(20.5% 0 0);--destructive:oklch(57.7% .245 27.325);--border:oklch(92.2% 0 0);--input:oklch(92.2% 0 0);--ring:oklch(70.8% 0 0);--chart-1:oklch(64.6% .222 41.116);--chart-2:oklch(60% .118 184.704);--chart-3:oklch(39.8% .07 227.392);--chart-4:oklch(82.8% .189 84.429);--chart-5:oklch(76.9% .188 70.08);--sidebar:oklch(98.5% 0 0);--sidebar-foreground:oklch(14.5% 0 0);--sidebar-primary:oklch(20.5% 0 0);--sidebar-primary-foreground:oklch(98.5% 0 0);--sidebar-accent:oklch(97% 0 0);--sidebar-accent-foreground:oklch(20.5% 0 0);--sidebar-border:oklch(92.2% 0 0);--sidebar-ring:oklch(70.8% 0 0)}.dark{--background:oklch(14.5% 0 0);--foreground:oklch(98.5% 0 0);--card:oklch(20.5% 0 0);--card-foreground:oklch(98.5% 0 0);--popover:oklch(20.5% 0 0);--popover-foreground:oklch(98.5% 0 0);--primary:oklch(92.2% 0 0);--primary-foreground:oklch(20.5% 0 0);--secondary:oklch(26.9% 0 0);--secondary-foreground:oklch(98.5% 0 0);--muted:oklch(26.9% 0 0);--muted-foreground:oklch(70.8% 0 0);--accent:oklch(26.9% 0 0);--accent-foreground:oklch(98.5% 0 0);--destructive:oklch(70.4% .191 22.216);--border:oklch(100% 0 0/.1);--input:oklch(100% 0 0/.15);--ring:oklch(55.6% 0 0);--chart-1:oklch(48.8% .243 264.376);--chart-2:oklch(69.6% .17 162.48);--chart-3:oklch(76.9% .188 70.08);--chart-4:oklch(62.7% .265 303.9);--chart-5:oklch(64.5% .246 16.439);--sidebar:oklch(20.5% 0 0);--sidebar-foreground:oklch(98.5% 0 0);--sidebar-primary:oklch(48.8% .243 264.376);--sidebar-primary-foreground:oklch(98.5% 0 0);--sidebar-accent:oklch(26.9% 0 0);--sidebar-accent-foreground:oklch(98.5% 0 0);--sidebar-border:oklch(100% 0 0/.1);--sidebar-ring:oklch(55.6% 0 0)}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}@keyframes pulse{50%{opacity:.5}}@keyframes enter{0%{opacity:var(--tw-enter-opacity,1);transform:translate3d(var(--tw-enter-translate-x,0),var(--tw-enter-translate-y,0),0)scale3d(var(--tw-enter-scale,1),var(--tw-enter-scale,1),var(--tw-enter-scale,1))rotate(var(--tw-enter-rotate,0));filter:blur(var(--tw-enter-blur,0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity,1);transform:translate3d(var(--tw-exit-translate-x,0),var(--tw-exit-translate-y,0),0)scale3d(var(--tw-exit-scale,1),var(--tw-exit-scale,1),var(--tw-exit-scale,1))rotate(var(--tw-exit-rotate,0));filter:blur(var(--tw-exit-blur,0))}} diff --git a/TrackingToolWeb/static/assets/index-Bbb87N2h.js b/TrackingToolWeb/static/assets/index-Bbb87N2h.js new file mode 100644 index 0000000..21bb33a --- /dev/null +++ b/TrackingToolWeb/static/assets/index-Bbb87N2h.js @@ -0,0 +1,3805 @@ +var Vu=function(r,t){return(Vu=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var o in n)n.hasOwnProperty(o)&&(e[o]=n[o])})(r,t)};function _t(r,t){function e(){this.constructor=r}Vu(r,t),r.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function J(r,t,e,n){return new(e||(e=Promise))((function(o,a){function i(c){try{u(n.next(c))}catch(l){a(l)}}function s(c){try{u(n.throw(c))}catch(l){a(l)}}function u(c){c.done?o(c.value):new e((function(l){l(c.value)})).then(i,s)}u((n=n.apply(r,[])).next())}))}function Q(r,t){var e,n,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(u){return function(c){return(function(l){if(e)throw new TypeError("Generator is already executing.");for(;i;)try{if(e=1,n&&(o=2&l[0]?n.return:l[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,l[1])).done)return o;switch(n=0,o&&(l=[2&l[0],o.value]),l[0]){case 0:case 1:o=l;break;case 4:return i.label++,{value:l[1],done:!1};case 5:i.label++,n=l[1],l=[0];continue;case 7:l=i.ops.pop(),i.trys.pop();continue;default:if(!(o=(o=i.trys).length>0&&o[o.length-1])&&(l[0]===6||l[0]===2)){i=0;continue}if(l[0]===3&&(!o||l[1]>o[0]&&l[1]0;)n=Math.random()*t|0,e=r[--t],r[t]=r[n],r[n]=e}function mo(r,t,e){return Math.max(r,Math.min(t,e))}function li(r){return r%2==0?r:r+1}function ju(r){for(var t=0,e=0;e=e?o():setTimeout(i,s)}};i()}))}function Xu(r,t){for(var e=1,n=-1,o=0;o=0)e*=r[o];else if(r[o]===-1){if(n!==-1)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+n+" and dim "+o);n=o}else if(r[o]<0)throw Error("Shapes can not be < 0. Found "+r[o]+" at dim "+o);if(n===-1){if(t>0&&t!==e)throw Error("Size("+t+") must match the product of shape "+r);return r}if(e===0)throw Error("Cannot infer the missing size in ["+r+"] when there are 0 elements");if(t%e!=0)throw Error("The implicit shape can't be a fractional number. Got "+t+" / "+e);var a=r.slice();return a[n]=t/e,a}function Le(r,t){var e=t.length;return E((r=r==null?t.map((function(n,o){return o})):[].concat(r)).every((function(n){return n>=-e&&ns)&&r[s]===1&&(e.push(r[s]),n.push(s)),a[i]<=s&&i++}r[s]!==1&&(e.push(r[s]),n.push(s))}return{newShape:e,keptDims:n}}function Qn(r,t){var e=null;if(r==null||r==="float32")e=new Float32Array(t);else if(r==="int32")e=new Int32Array(t);else{if(r!=="bool")throw new Error("Unknown data type "+r);e=new Uint8Array(t)}return e}function wr(r,t){var e=null;if(r==null||r==="float32")e=new Float32Array(t);else if(r==="int32")e=new Int32Array(t);else if(r==="bool")e=new Uint8Array(t);else{if(r!=="string")throw new Error("Unknown data type "+r);e=new Array(t)}return e}function Yu(r,t){for(var e=0;e=0;--n)e[n]=e[n+1]*r[n+1];return e}function fi(r,t,e){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(r)&&(r=Yt(r)),e&&Yu(r,t),(function(a,i){return a instanceof Float32Array&&i==="float32"||a instanceof Int32Array&&i==="int32"||a instanceof Uint8Array&&i==="bool"})(r,t))return r;if(t==null||t==="float32"||t==="complex64")return new Float32Array(r);if(t==="int32")return new Int32Array(r);if(t==="bool"){for(var n=new Uint8Array(r.length),o=0;o=0,(function(){return"Tensor must have a shape comprised of positive integers but got shape ["+r+"]."}))}))}function tc(r,t){return t===void 0&&(t="utf-8"),t=t||"utf-8",M().platform.encode(r,t)}function Cr(r,t){return t===void 0&&(t="utf-8"),t=t||"utf-8",M().platform.decode(r,t)}function Ba(r,t,e){if(t===0)return 0;if(t===1)return r[0];for(var n=r[r.length-1],o=0;o0?p:"")+" "}console.log("%c"+u+" %c"+s+" %c"+c+"D "+h+" %c"+l+" %c"+f+" %c"+i,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},r})(),eu=20,lr=3,ha=7;function pp(r,t,e,n){var o=xt(t),a=(function(c,l,h,f){var d=Z(l),p=f[f.length-1],m=new Array(p).fill(0),v=l.length,g=h==="complex64"?fr(c):c;if(v>1)for(var x=0;xeu){var b=lr*v,y=Array.from(l.slice(0,b)),w=Array.from(l.slice((g-lr)*v,g*v));return f==="complex64"&&(y=fr(y),w=fr(w)),["["+y.map((function(B,U){return hr(B,p[U],f)})).join(", ")+", ..., "+w.map((function(B,U){return hr(B,p[g-lr+U],f)})).join(", ")+"]"]}return["["+(f==="complex64"?fr(l):Array.from(l)).map((function(B,U){return hr(B,p[U],f)})).join(", ")+"]"]}var _=h.slice(1),S=d.slice(1),k=d[0]*v,I=[];if(g>eu){for(var R=0;R=this.shape[n]){var s="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(s)}n++}for(var u=t[t.length-1],c=0;c0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+s+" data ids) after running '"+t+"'")},r.prototype.runKernelFunc=function(t,e,n,o,a,i,s){var u,c=this;i===void 0&&(i=[]),s===void 0&&(s=[]);var l=[],h=this.isTapeOn();o==null&&(o=this.state.activeScope!=null?this.state.activeScope.name:"");var f,d=function(x){h&&(l=x.map((function(b){return c.keep(c.clone(b))})))},p=this.state.numBytes,m=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var v,g=si(o,this.backendName);return f=g!=null?function(){var x=c.backend.numDataIds();v=g.kernelFunc({inputs:e,attrs:a,backend:c.backend});var b=Array.isArray(v)?v:[v];c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(o,x,b);var y=b.map((function(_){var S=_.dataId,k=_.shape,I=_.dtype;return c.makeTensorFromDataId(S,k,I)})),w=y.filter((function(_,S){return s[S]}));return d((i||[]).slice().concat(w)),y}:function(){var x=c.backend.numDataIds();v=c.tidy((function(){return t(c.backend,d)}));var b=Array.isArray(v)?v:[v];return c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(o,x,b),b},this.scopedRun((function(){return c.state.kernelDepth++}),(function(){return c.state.kernelDepth--}),(function(){u=c.ENV.getBool("DEBUG")?c.profiler.profileKernel(o,e,(function(){return f()})):f()})),h&&this.addTapeNode(o,e,u,n,l),this.state.profiling&&this.state.activeProfile.kernels.push({name:o,bytesAdded:this.state.numBytes-p,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-m,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map((function(x){return e[x].shape})),outputShapes:u.map((function(x){return x.shape}))}),Array.isArray(v)?u:u[0]},r.prototype.makeTensor=function(t,e,n,o){if(t==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",o=o||this.backend;var a=t;n==="string"&&un(t[0])&&(a=t.map((function(l){return tc(l)})));var i=o.write(a,e,n),s=new we(e,n,i,this.nextTensorId());if(this.incRef(s,o),n==="string"){var u=this.state.tensorInfo.get(i),c=Qu(a);this.state.numBytes+=c-u.bytes,u.bytes=c}return s},r.prototype.makeTensorFromDataId=function(t,e,n,o){var a=new we(e,n=n||"float32",t,this.nextTensorId());return this.incRef(a,o),a},r.prototype.makeVariable=function(t,e,n,o){e===void 0&&(e=!0),n=n||this.nextVariableId().toString(),o!=null&&o!==t.dtype&&(t=t.asType(o));var a=new An(t,e,n,this.nextTensorId());if(this.state.registeredVariables[a.name]!=null)throw new Error("Variable with name "+a.name+" was already registered");return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a},r.prototype.incRef=function(t,e){var n=this.state.tensorInfo.has(t.dataId)?this.state.tensorInfo.get(t.dataId).refCount:0;if(this.state.numTensors++,t.dtype==="string"&&this.state.numStringTensors++,n===0){this.state.numDataBuffers++;var o=0;t.dtype!=="complex64"&&t.dtype!=="string"&&(o=t.size*hi(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:o,refCount:0}),this.state.numBytes+=o}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof An||this.track(t)},r.prototype.disposeTensor=function(t){if(this.state.tensorInfo.has(t.dataId)){this.state.numTensors--,t.dtype==="string"&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId);e.refCount<=1?(t.dtype!=="complex64"&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(t.dataId),this.state.tensorInfo.delete(t.dataId)):this.state.tensorInfo.get(t.dataId).refCount--}},r.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e)}},r.prototype.disposeVariable=function(t){this.disposeTensor(t),this.state.registeredVariables[t.name]!=null&&delete this.state.registeredVariables[t.name]},r.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,t.reasons==null&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},r.prototype.profile=function(t){return J(this,void 0,void 0,(function(){var e,n;return Q(this,(function(o){return this.state.profiling=!0,e=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map((function(a){return a.totalBytesSnapshot}))),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]}))}))},r.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&this.state.kernelDepth===0},r.prototype.addTapeNode=function(t,e,n,o,a){var i=this,s={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:n,saved:a},u=Hu(t);u!=null&&(o=u.gradFunc),o!=null&&(s.gradient=function(c){return c=c.map((function(l,h){if(l==null){var f=n[h],d=ar(f.size,f.dtype);return i.makeTensor(d,f.shape,f.dtype)}return l})),o(c.length>1?c:c[0],a)}),this.state.activeTape.push(s)},r.prototype.keep=function(t){return t.kept=!0,t},r.prototype.startTape=function(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++},r.prototype.endTape=function(){this.state.gradientDepth--},r.prototype.startScope=function(t){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e},r.prototype.endScope=function(t){for(var e=this,n=vi(t),o=new Set(n.map((function(u){return u.id}))),a=0;a0,(function(){return"gradients() received an empty list of xs."})),n!=null&&n.dtype!=="float32")throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");var i=this.scopedRun((function(){return a.startTape()}),(function(){return a.endTape()}),(function(){return a.tidy("forward",t)}));E(i instanceof we,(function(){return"The result y returned by f() must be a tensor."}));var s=(function(u,c,l){for(var h={},f={},d=0;d=0;d--)for(p=(_=u[d]).inputs,x=0;x<_.outputs.length;x++)if(b[_.outputs[x].id]){for(var m in p)b[p[m].id]=!0,y[_.id]=!0;break}var w=[];for(d=0;d0)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",(function(){var u,c,l={};l[i.id]=n??(u=i.shape,c=di(Z(u),"float32"),A.makeTensor(c,u,"float32")),(function(f,d,p){for(var m=function(g){var x=d[g],b=[];if(x.outputs.forEach((function(S){var k=f[S.id];k!=null?b.push(k):b.push(null)})),x.gradient==null)throw new Error("Cannot compute gradient: gradient function not found for "+x.kernelName+".");var y=x.gradient(b),w=function(S){if(!(S in y))throw new Error("Cannot backprop through input "+S+". Available gradients found: "+Object.keys(y)+".");var k=p((function(){return y[S]()}));if(k.dtype!=="float32")throw new Error("Error in gradient for op "+x.kernelName+". The gradient of input "+S+" must have 'float32' dtype, but has '"+k.dtype+"'");var I=x.inputs[S];if(!Ne(k.shape,I.shape))throw new Error("Error in gradient for op "+x.kernelName+". The gradient of input '"+S+"' has shape '"+k.shape+"', which does not match the shape of the input '"+I.shape+"'");if(f[I.id]==null)f[I.id]=k;else{var R=f[I.id];f[I.id]=R.add(k),R.dispose()}};for(var _ in x.inputs)w(_)},v=d.length-1;v>=0;v--)m(v)})(l,s,(function(f){return a.tidy(f)}));var h=e.map((function(f){return l[f.id]}));return a.state.gradientDepth===0&&(a.state.activeTape.forEach((function(f){for(var d=0,p=f.saved;d"u")throw new Error("Could not find a global object");e=self}fa=e}return fa})();if(r._tfengine==null){var t=new Gu(r);r._tfengine=new gp(t)}return(function(e){ii=e})(r._tfengine.ENV),Ft=function(){return r._tfengine},r._tfengine})();function ic(){return typeof window<"u"&&window.document!=null||typeof WorkerGlobalScope<"u"}var Vt=M();Vt.registerFlag("DEBUG",(function(){return!1}),(function(r){r&&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.")})),Vt.registerFlag("IS_BROWSER",(function(){return ic()})),Vt.registerFlag("IS_NODE",(function(){return typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0})),Vt.registerFlag("IS_CHROME",(function(){return typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)})),Vt.registerFlag("PROD",(function(){return!1})),Vt.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(function(){return Vt.getBool("DEBUG")})),Vt.registerFlag("DEPRECATION_WARNINGS_ENABLED",(function(){return!0})),Vt.registerFlag("IS_TEST",(function(){return!1}));var _r,ct,it,Cn={},da={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function sc(r,t){Cn[r]=t}function Bt(r){r in Cn||(Cn[r]=(function(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var n=(function(o){if(typeof OffscreenCanvas<"u"&&o===2)return new OffscreenCanvas(300,150);if(typeof document<"u")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")})(e);return n.addEventListener("webglcontextlost",(function(o){o.preventDefault(),delete Cn[e]}),!1),e===1?n.getContext("webgl",da)||n.getContext("experimental-webgl",da):n.getContext("webgl2",da)})(r));var t=Cn[r];return t.isContextLost()?(delete Cn[r],Bt(r)):(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),Cn[r])}function To(r,t){return[t,r]}function gr(r){var t=Z(r);return go(Math.ceil(t/4))}function Lr(r,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(r/2))]}function mi(r,t){var e,n,o,a,i,s,u,c,l,h=r;return M().getNumber("WEBGL_VERSION")===2?(e=h.R32F,n=h.R16F,o=h.RGBA16F,a=h.RGBA32F,i=h.RED,s=4,u=1,c=h.HALF_FLOAT,l=h.FLOAT):(e=r.RGBA,n=r.RGBA,o=r.RGBA,a=h.RGBA,i=r.RGBA,s=4,u=4,c=t!=null?t.HALF_FLOAT_OES:null,l=r.FLOAT),{internalFormatFloat:e,internalFormatHalfFloat:n,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:a,textureFormatFloat:i,downloadTextureFormat:r.RGBA,downloadUnpackNumChannels:s,defaultNumChannels:u,textureTypeHalfFloat:c,textureTypeFloat:l}}function X(r,t,e){var n=e();return t&&(function(o){var a=o.getError();if(a!==o.NO_ERROR)throw new Error("WebGL Error: "+cc(o,a))})(r),n}(function(r){r[r.DENSE=0]="DENSE",r[r.SHARED_BATCH=1]="SHARED_BATCH"})(_r||(_r={})),(function(r){r[r.RENDER=0]="RENDER",r[r.UPLOAD=1]="UPLOAD",r[r.PIXELS=2]="PIXELS",r[r.DOWNLOAD=3]="DOWNLOAD"})(ct||(ct={})),(function(r){r[r.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",r[r.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",r[r.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",r[r.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",r[r.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(it||(it={}));var yp=596e-10,xp=65504;function uc(r){return!!(M().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||r===0||ype||t>e)throw n="["+r+"x"+t+"]",new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU "+("["+e+"x"+e+"]")+".")}function yc(r,t){return Jt(r,t,(function(){return r.createFramebuffer()}),"Unable to create WebGLFramebuffer.")}function Ga(r,t,e,n,o,a,i,s){var u=r.getAttribLocation(e,n);return u!==-1&&(X(r,t,(function(){return r.bindBuffer(r.ARRAY_BUFFER,o)})),X(r,t,(function(){return r.vertexAttribPointer(u,a,r.FLOAT,!1,i,s)})),X(r,t,(function(){return r.enableVertexAttribArray(u)})),!0)}function xc(r,t,e,n){Ec(r,n),X(r,t,(function(){return r.activeTexture(r.TEXTURE0+n)})),X(r,t,(function(){return r.bindTexture(r.TEXTURE_2D,e)}))}function bc(r,t,e,n){return Jt(r,t,(function(){return r.getUniformLocation(e,n)}),'uniform "'+n+'" not present in program.')}function wc(r,t,e){return r.getUniformLocation(t,e)}function Cc(r,t,e,n,o,a){X(r,t,(function(){return xc(r,t,n,a)})),X(r,t,(function(){return r.uniform1i(o,a)}))}function ho(r,t,e,n){X(r,t,(function(){return r.bindFramebuffer(r.FRAMEBUFFER,n)})),X(r,t,(function(){return r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0)}))}function Ha(r,t,e){X(r,t,(function(){return r.bindFramebuffer(r.FRAMEBUFFER,e)})),X(r,t,(function(){return r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,null,0)}))}function vr(r){var t=r.checkFramebufferStatus(r.FRAMEBUFFER);if(t!==r.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+_c(r,t))}function _c(r,t){switch(t){case r.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case r.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}function Jt(r,t,e,n){var o=X(r,t,(function(){return e()}));if(o==null)throw new Error(n);return o}function Ec(r,t){var e=r.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+r.TEXTURE0;if(ne)throw new Error("textureUnit must be in "+("[gl.TEXTURE0, gl.TEXTURE"+e+"]")+".")}function Er(r,t){return t===void 0&&(t=2),Z(r.slice(0,r.length-t))}function Ir(r){if(r.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[r.length>1?r[r.length-2]:1,r[r.length-1]]}function fo(r){var t=[1,1,1];return r.length===0||r.length===1&&r[0]===1||(t=[Er(r)].concat(Ir(r))),t}function Ic(r,t){var e;t===void 0&&(t=!1);var n=M().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n*=2,(r=r.map((function(c,l){return l>=r.length-2?li(r[l]):r[l]}))).length===1&&(r=[2,r[0]])),r.length!==2){var o=sn(r);r=o.newShape}var a=Z(r);if(r.length<=1&&a<=n)return[1,a];if(r.length===2&&r[0]<=n&&r[1]<=n)return r;if(r.length===3&&r[0]*r[1]<=n&&r[2]<=n)return[r[0]*r[1],r[2]];if(r.length===3&&r[0]<=n&&r[1]*r[2]<=n)return[r[0],r[1]*r[2]];if(r.length===4&&r[0]*r[1]*r[2]<=n&&r[3]<=n)return[r[0]*r[1]*r[2],r[3]];if(r.length===4&&r[0]<=n&&r[1]*r[2]*r[3]<=n)return[r[0],r[1]*r[2]*r[3]];if(t){var i=Er(r),s=2,u=2;return r.length&&(s=(e=Ir(r))[0],u=e[1]),go(a=i*(s/2)*(u/2)).map((function(c){return 2*c}))}return go(a)}function $r(r){return r%2==0}function mr(r,t){if(Ne(r=r.slice(-2),t=t.slice(-2))||!r.length||!t.length||r[0]===0||r[1]===0||t[0]===0||t[1]===0)return!0;if(r.length!==t.length){var e=r.slice(-1)[0],n=t.slice(-1)[0];if(e===n||$r(e)&&$r(n)&&(r[0]===1||t[0]===1))return!0}return r[1]===t[1]&&$r(r[0])&&$r(t[0])}function Rc(r){if(uo==null){var t=Bt(r);uo=t.getParameter(t.MAX_TEXTURE_SIZE)}return uo}function kc(r){if(co==null){var t=Bt(r);co=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,co)}function Sc(r){if(r===0)return 0;var t=Bt(r);return lt(t,"EXT_disjoint_timer_query_webgl2")&&r===2?2:lt(t,"EXT_disjoint_timer_query")?1:0}function lt(r,t){return r.getExtension(t)!=null}function qa(r){try{if(Bt(r)!=null)return!0}catch{return!1}return!1}function Ac(r){if(r===0)return!1;var t=Bt(r);if(r===1){if(!lt(t,"OES_texture_float"))return!1}else if(!lt(t,"EXT_color_buffer_float"))return!1;return ja(t)}function Dc(r){if(r===0)return!1;var t=Bt(r);if(r!==1){if(lt(t,"EXT_color_buffer_float"))return ja(t);if(lt(t,"EXT_color_buffer_half_float")){var e=t.getExtension("EXT_color_buffer_half_float");return(function(n,o){var a=mi(n,o),i=n.createTexture();n.bindTexture(n.TEXTURE_2D,i),n.texImage2D(n.TEXTURE_2D,0,a.internalFormatHalfFloat,1,1,0,a.textureFormatFloat,a.textureTypeHalfFloat,null);var s=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,s),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,i,0);var u=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(i),n.deleteFramebuffer(s),u})(t,e)}return!1}return!!lt(t,"OES_texture_float")&&!!lt(t,"WEBGL_color_buffer_float")&&ja(t)}function ja(r){var t=mi(r),e=r.createTexture();r.bindTexture(r.TEXTURE_2D,e),r.texImage2D(r.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);var n=r.createFramebuffer();r.bindFramebuffer(r.FRAMEBUFFER,n),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0);var o=r.checkFramebufferStatus(r.FRAMEBUFFER)===r.FRAMEBUFFER_COMPLETE;return r.bindTexture(r.TEXTURE_2D,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteTexture(e),r.deleteFramebuffer(n),o}function Tc(r){return r===2&&Bt(r).fenceSync!=null}var wp=Object.freeze({callAndCheck:X,canBeRepresented:uc,getWebGLErrorMessage:cc,getExtensionOrThrow:pr,createVertexShader:lc,createFragmentShader:hc,createProgram:fc,linkProgram:dc,validateProgram:lo,createStaticVertexBuffer:pc,createStaticIndexBuffer:vc,getNumChannels:function(){return M().getNumber("WEBGL_VERSION")===2?1:4},createTexture:mc,validateTextureSize:gc,createFramebuffer:yc,bindVertexBufferToProgramAttribute:Ga,bindTextureUnit:xc,unbindTextureUnit:function(r,t,e){Ec(r,e),X(r,t,(function(){return r.activeTexture(r.TEXTURE0+e)})),X(r,t,(function(){return r.bindTexture(r.TEXTURE_2D,null)}))},getProgramUniformLocationOrThrow:bc,getProgramUniformLocation:wc,bindTextureToProgramUniformSampler:Cc,bindCanvasToFramebuffer:function(r,t){X(r,t,(function(){return r.bindFramebuffer(r.FRAMEBUFFER,null)})),X(r,t,(function(){return r.viewport(0,0,r.canvas.width,r.canvas.height)})),X(r,t,(function(){return r.scissor(0,0,r.canvas.width,r.canvas.height)}))},bindColorTextureToFramebuffer:ho,unbindColorTextureFromFramebuffer:Ha,validateFramebuffer:vr,getFramebufferErrorMessage:_c,getBatchDim:Er,getRowsCols:Ir,getShapeAs3D:fo,getTextureShapeFromLogicalShape:Ic,isReshapeFree:mr,getWebGLMaxTextureSize:Rc,resetMaxTextureSize:function(){uo=null},resetMaxTexturesInShader:function(){co=null},getMaxTexturesInShader:kc,getWebGLDisjointQueryTimerVersion:Sc,hasExtension:lt,isWebGLVersionEnabled:qa,isCapableOfRenderingToFloatTexture:Ac,isDownloadFloatTextureEnabled:Dc,isWebGLFenceEnabled:Tc}),ne=M();function Cp(){M().set("PROD",!0)}function _p(){M().set("DEBUG",!0)}function Ep(){M().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function gi(r){M().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Ip(){A.disposeVariables()}function Rp(){return A}function kp(){return A.memory()}function Sp(r){return A.profile(r)}function K(r,t){return A.tidy(r,t)}function Ze(r){vi(r).forEach((function(t){return t.dispose()}))}function Fc(r){return A.keep(r)}function Ap(r){return A.time(r)}function Dp(r){return A.setBackend(r)}function Tp(){return A.ready()}function Fp(){return A.backendName}function Np(r){A.removeBackend(r)}function Pp(r){return A.findBackend(r)}function Mp(r){return A.findBackendFactory(r)}function Op(r,t,e){return e===void 0&&(e=1),A.registerBackend(r,t,e)}function Bp(){return A.backend}function Lp(r,t){M().setPlatform(r,t)}function xo(){for(var r=[],t=0;t0,(function(){return"Element arr["+s.join("][")+"] should be a primitive, but is an array of "+a.length+" elements"})),E(a.length===i[0],(function(){return"Element arr["+s.join("][")+"] should have "+i[0]+" elements, but has "+a.length+" elements"}));for(var u=i.slice(1),c=0;c=0&&(o=n),nu(n,o,t,e),r==null||!je(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string"){var a=r==null?"null":r.constructor.name;throw new Error("Argument '"+t+"' passed to '"+e+"' must be a Tensor or TensorLike, but got '"+a+"'")}var i=Pt(r,o);je(r)||Array.isArray(r)||(r=[r]);var s=o!=="string"?fi(r,o,M().getBool("DEBUG")):Yt(r,[],!0);return A.makeTensor(s,i,o)}function Rr(r,t,e,n){if(n===void 0&&(n="numeric"),!Array.isArray(r))throw new Error("Argument "+t+" passed to "+e+" must be a `Tensor[]` or `TensorLike[]`");return r.map((function(o,a){return C(o,t+"["+a+"]",e)}),n)}function yi(r,t){for(var e=0;e=0&&t0})),ne.registerFlag("WEBGL_VERSION",(function(){return qa(2)?2:qa(1)?1:0})),ne.registerFlag("WEBGL_BUFFER_SUPPORTED",(function(){return ne.get("WEBGL_VERSION")===2})),ne.registerFlag("WEBGL_CPU_FORWARD",(function(){return!0})),ne.registerFlag("WEBGL_FORCE_F16_TEXTURES",(function(){return!1})),ne.registerFlag("WEBGL_PACK",(function(){return ne.getBool("HAS_WEBGL")})),ne.registerFlag("WEBGL_PACK_NORMALIZATION",(function(){return ne.getBool("WEBGL_PACK")})),ne.registerFlag("WEBGL_PACK_CLIP",(function(){return ne.getBool("WEBGL_PACK")})),ne.registerFlag("WEBGL_PACK_DEPTHWISECONV",(function(){return!1})),ne.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(function(){return ne.getBool("WEBGL_PACK")})),ne.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(function(){return ne.getBool("WEBGL_PACK")})),ne.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(function(){return ne.getBool("WEBGL_PACK")})),ne.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(function(){return ne.getBool("WEBGL_PACK")})),ne.registerFlag("WEBGL_PACK_REDUCE",(function(){return ne.getBool("WEBGL_PACK")})),ne.registerFlag("WEBGL_LAZILY_UNPACK",(function(){return ne.getBool("WEBGL_PACK")})),ne.registerFlag("WEBGL_CONV_IM2COL",(function(){return ne.getBool("WEBGL_PACK")})),ne.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(function(){return Rc(ne.getNumber("WEBGL_VERSION"))})),ne.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(function(){return kc(ne.getNumber("WEBGL_VERSION"))})),ne.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(function(){var r=ne.getNumber("WEBGL_VERSION");return r===0?0:Sc(r)})),ne.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(function(){return ne.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(r=navigator.userAgent||navigator.vendor||window.opera,!(/(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(r)||/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(r.substr(0,4))));var r})),ne.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(function(){return Ac(ne.getNumber("WEBGL_VERSION"))})),ne.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(function(){return!ne.getBool("WEBGL_FORCE_F16_TEXTURES")&&ne.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")})),ne.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(function(){return Dc(ne.getNumber("WEBGL_VERSION"))})),ne.registerFlag("WEBGL_FENCE_API_ENABLED",(function(){return Tc(ne.getNumber("WEBGL_VERSION"))})),ne.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(function(){return ne.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0})),oc=gi;var Ue=D({complex_:function(r,t){var e=C(r,"real","complex"),n=C(t,"imag","complex");return me(e.shape,n.shape,"real and imag shapes, "+e.shape+" and "+n.shape+", must match in call to tf.complex()."),A.runKernelFunc((function(o){return o.complex(e,n)}),{$real:e,$imag:n})}}),ut=D({real_:function(r){var t=C(r,"input","real");return A.runKernelFunc((function(e){return e.real(t)}),{$input:t})}}),yt=D({imag_:function(r){var t=C(r,"input","imag");return A.runKernelFunc((function(e){return e.imag(t)}),{$input:t})}});function Ge(r,t,e){return pn(r,t,Pt(r,e),e)}function pn(r,t,e,n){if(n==null&&(n=or(r)),n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!je(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="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(t!=null){pi(t);var o=Z(t),a=Z(e);E(o===a,(function(){return"Based on the provided shape, ["+t+"], the tensor should have "+o+" values but has "+a}));for(var i=0;i1)return Ce([0],n);var o=ar(Math.abs(Math.ceil((t-r)/e)),n);t=1,(function(){return"Pass at least one tensor to concat"}));var e=Rr(r,"tensors","concat");e[0].dtype==="complex64"&&e.forEach((function(s){if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor + with dtype `+s.dtype+". ")})),t=Le(t,e[0].shape)[0];var n=Dn(e.map((function(s){return s.shape})),t);if(Z(n)===0)return Ge([],n);if((e=e.filter((function(s){return s.size>0}))).length===1)return e[0];var o=e.map((function(s){return s.shape}));Pc(o,t);var a=e,i={axis:t};return A.runKernelFunc((function(s){return s.concat(e,t)}),a,(function(s){var u=o.map((function(c){return c[t]}));return Po(s,u,t).map((function(c){return function(){return c}}))}),"Concat",i)}}),Wc=D({concat1d_:function(r){return Pe(r,0)}}),zc=D({concat2d_:function(r,t){return Pe(r,t)}}),Uc=D({concat3d_:function(r,t){return Pe(r,t)}}),Vc=D({concat4d_:function(r,t){return Pe(r,t)}}),Po=D({split_:function(r,t,e){e===void 0&&(e=0);var n,o=C(r,"x","split");return e=Le(e,o.shape)[0],typeof t=="number"?(E(o.shape[e]%t==0,(function(){return"Number of splits must evenly divide the axis."})),n=new Array(t).fill(o.shape[e]/t)):(E(o.shape[e]===t.reduce((function(a,i){return a+i})),(function(){return"The sum of sizes must match the size of the axis dimension."})),n=t),A.runKernelFunc((function(a){return a.split(o,n,e)}),{$x:o},(function(a){return{$x:function(){return Pe(a,e)}}}))}});function Pn(r,t){return r(t={exports:{}},t.exports),t.exports}var Wp=Pn((function(r){(function(t,e,n){function o(s){var u,c=this,l=(u=4022871197,function(h){h=h.toString();for(var f=0;f>>0,u=(d*=u)>>>0,u+=4294967296*(d-=u)}return 23283064365386963e-26*(u>>>0)});c.next=function(){var h=2091639*c.s0+23283064365386963e-26*c.c;return c.s0=c.s1,c.s1=c.s2,c.s2=h-(c.c=0|h)},c.c=1,c.s0=l(" "),c.s1=l(" "),c.s2=l(" "),c.s0-=l(s),c.s0<0&&(c.s0+=1),c.s1-=l(s),c.s1<0&&(c.s1+=1),c.s2-=l(s),c.s2<0&&(c.s2+=1),l=null}function a(s,u){return u.c=s.c,u.s0=s.s0,u.s1=s.s1,u.s2=s.s2,u}function i(s,u){var c=new o(s),l=u&&u.state,h=c.next;return h.int32=function(){return 4294967296*c.next()|0},h.double=function(){return h()+11102230246251565e-32*(2097152*h()|0)},h.quick=h,l&&(typeof l=="object"&&a(l,c),h.state=function(){return a(c,{})}),h}e&&e.exports?e.exports=i:this.alea=i})(0,r)})),zp=Pn((function(r){(function(t,e,n){function o(s){var u=this,c="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var h=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^h^h>>>8},s===(0|s)?u.x=s:c+=s;for(var l=0;l>>0)/4294967296};return h.double=function(){do var f=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(f===0);return f},h.int32=c.next,h.quick=h,l&&(typeof l=="object"&&a(l,c),h.state=function(){return a(c,{})}),h}e&&e.exports?e.exports=i:this.xor128=i})(0,r)})),Up=Pn((function(r){(function(t,e,n){function o(s){var u=this,c="";u.next=function(){var h=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^h^h<<1)|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,s===(0|s)?u.x=s:c+=s;for(var l=0;l>>4),u.next()}function a(s,u){return u.x=s.x,u.y=s.y,u.z=s.z,u.w=s.w,u.v=s.v,u.d=s.d,u}function i(s,u){var c=new o(s),l=u&&u.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var f=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(f===0);return f},h.int32=c.next,h.quick=h,l&&(typeof l=="object"&&a(l,c),h.state=function(){return a(c,{})}),h}e&&e.exports?e.exports=i:this.xorwow=i})(0,r)})),Vp=Pn((function(r){(function(t,e,n){function o(s){var u=this;u.next=function(){var c,l,h=u.x,f=u.i;return c=h[f],l=(c^=c>>>7)^c<<24,l^=(c=h[f+1&7])^c>>>10,l^=(c=h[f+3&7])^c>>>3,l^=(c=h[f+4&7])^c<<7,c=h[f+7&7],l^=(c^=c<<13)^c<<9,h[f]=l,u.i=f+1&7,l},(function(c,l){var h,f=[];if(l===(0|l))f[0]=l;else for(l=""+l,h=0;h0;--h)c.next()})(u,s)}function a(s,u){return u.x=s.x.slice(),u.i=s.i,u}function i(s,u){s==null&&(s=+new Date);var c=new o(s),l=u&&u.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var f=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(f===0);return f},h.int32=c.next,h.quick=h,l&&(l.x&&a(l,c),h.state=function(){return a(c,{})}),h}e&&e.exports?e.exports=i:this.xorshift7=i})(0,r)})),Gp=Pn((function(r){(function(t,e,n){function o(s){var u=this;u.next=function(){var c,l,h=u.w,f=u.X,d=u.i;return u.w=h=h+1640531527|0,l=f[d+34&127],c=f[d=d+1&127],l^=l<<13,c^=c<<17,l^=l>>>15,c^=c>>>12,l=f[d]=l^c,u.i=d,l+(h^h>>>16)|0},(function(c,l){var h,f,d,p,m,v=[],g=128;for(l===(0|l)?(f=l,l=null):(l+="\0",f=0,g=Math.max(g,l.length)),d=0,p=-32;p>>15,f^=f<<4,f^=f>>>13,p>=0&&(m=m+1640531527|0,d=(h=v[127&p]^=f+m)==0?d+1:0);for(d>=128&&(v[127&(l&&l.length||0)]=-1),d=127,p=512;p>0;--p)f=v[d+34&127],h=v[d=d+1&127],f^=f<<13,h^=h<<17,f^=f>>>15,h^=h>>>12,v[d]=f^h;c.w=m,c.X=v,c.i=d})(u,s)}function a(s,u){return u.i=s.i,u.w=s.w,u.X=s.X.slice(),u}function i(s,u){s==null&&(s=+new Date);var c=new o(s),l=u&&u.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var f=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(f===0);return f},h.int32=c.next,h.quick=h,l&&(l.X&&a(l,c),h.state=function(){return a(c,{})}),h}e&&e.exports?e.exports=i:this.xor4096=i})(0,r)})),Hp=Pn((function(r){(function(t,e,n){function o(s){var u=this,c="";u.next=function(){var h=u.b,f=u.c,d=u.d,p=u.a;return h=h<<25^h>>>7^f,f=f-d|0,d=d<<24^d>>>8^p,p=p-h|0,u.b=h=h<<20^h>>>12^f,u.c=f=f-d|0,u.d=d<<16^f>>>16^p,u.a=p-h|0},u.a=0,u.b=0,u.c=-1640531527,u.d=1367130551,s===Math.floor(s)?(u.a=s/4294967296|0,u.b=0|s):c+=s;for(var l=0;l>>0)/4294967296};return h.double=function(){do var f=((c.next()>>>11)+(c.next()>>>0)/4294967296)/2097152;while(f===0);return f},h.int32=c.next,h.quick=h,l&&(typeof l=="object"&&a(l,c),h.state=function(){return a(c,{})}),h}e&&e.exports?e.exports=i:this.tychei=i})(0,r)})),_n=Pn((function(r){(function(t,e){var n,o=this,a=256,i=6,s="random",u=e.pow(a,i),c=e.pow(2,52),l=2*c,h=a-1;function f(g,x,b){var y=[],w=m((function k(I,R){var F,T=[],L=typeof I;if(R&&L=="object")for(F in I)try{T.push(k(I[F],R-1))}catch{}return T.length?T:L=="string"?I:I+"\0"})((x=x==1?{entropy:!0}:x||{}).entropy?[g,v(t)]:g??(function(){try{var k;return n&&(k=n.randomBytes)?k=k(a):(k=new Uint8Array(a),(o.crypto||o.msCrypto).getRandomValues(k)),v(k)}catch{var I=o.navigator,R=I&&I.plugins;return[+new Date,o,R,o.screen,v(t)]}})(),3),y),_=new d(y),S=function(){for(var k=_.g(i),I=u,R=0;k=l;)k/=2,I/=2,R>>>=1;return(k+R)/I};return S.int32=function(){return 0|_.g(4)},S.quick=function(){return _.g(4)/4294967296},S.double=S,m(v(_.S),t),(x.pass||b||function(k,I,R,F){return F&&(F.S&&p(F,_),k.state=function(){return p(_,{})}),R?(e[s]=k,I):k})(S,w,"global"in x?x.global:this==e,x.state)}function d(g){var x,b=g.length,y=this,w=0,_=y.i=y.j=0,S=y.S=[];for(b||(g=[b++]);w=1||s===0);var u=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*a*u,n=this.mean+this.stdDev*i*u,this.truncated&&!this.isValidTruncated(e)||(o=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},r.prototype.convertValue=function(t){return this.dtype==null||this.dtype==="float32"?t:Math.round(t)},r.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},r})(),qp=(function(){function r(t,e,n,o){this.alpha=t,this.beta=1/e,this.dtype=n;var a=o||Math.random();this.randu=Mo(a.toString()),this.randn=new bi(0,1,n,!1,this.randu()),this.d=t<1?t+2/3:t-1/3,this.c=1/Math.sqrt(9*this.d)}return r.prototype.nextValue=function(){for(var t,e,n,o,a,i;;){do o=this.randn.nextValue(),i=1+this.c*o;while(i<=0);if(i*=i*i,e=1-.331*(t=o*o)*t,n=.5*t+this.d*(1-i+Math.log(i)),(a=this.randu())=1+t.length,(function(){return"input rank is "+n.rank+" but should be > than blockShape.length "+t.length})),E(e.length===t.length,(function(){return"crops.length is "+e.length+" but should be equal to blockShape.length "+t.length})),E(n.shape[0]%o==0,(function(){return"input tensor batch is "+n.shape[0]+" but is not divisible by the product of the elements of blockShape "+t.join(" * ")+" === "+o})),A.runKernelFunc((function(a){return a.batchToSpaceND(n,t,e)}),{$x:n},(function(a){return{$x:function(){return a.spaceToBatchND(t,e)}}}))}}),Hc=D({broadcastTo_:function(r,t){var e=C(r,"broadcastTo","x"),n=e.shape;if(t.some((function(u){return!(u>0)||u%1!=0})))throw new Error("broadcastTo(): Invalid broadcast shape ["+t+"].");if(t.lengthe.rank){for(var o=e.shape.slice();o.length=0;i--)if(e.shape[i]===t[i])a[i]=1;else if(e.shape[i]!==1)throw new Error("broadcastTo(): ["+n+"] cannot be broadcast to ["+t+"].");var s=a.map((function(u,c){return u>1?c:-1})).filter((function(u){return u>=0}));return s.length===0?e.clone():A.runKernelFunc((function(u){return u.tile(e,a)}),{input:e},(function(u){return{input:function(){return u.sum(s,!0)}}}))}}),qc=D({cast_:function(r,t){var e=C(r,"x","cast");if(!$u(t))throw new Error("Failed to cast to unknown dtype "+t);if(t==="string"&&e.dtype!=="string"||t!=="string"&&e.dtype==="string")throw new Error("Only strings can be casted to strings");var n={dtype:t};return A.runKernelFunc((function(o){return o.cast(e,t)}),{x:e},(function(o){return{x:function(){return o.clone()}}}),"Cast",n)}}),jc=D({clone_:function(r){var t=C(r,"x","clone",null);return A.runKernelFunc((function(){return A.makeTensorFromDataId(t.dataId,t.shape,t.dtype)}),{$x:t},(function(e){return{$x:function(){return e.toFloat()}}}))}}),Kc=D({cumsum_:function(r,t,e,n){t===void 0&&(t=0),e===void 0&&(e=!1),n===void 0&&(n=!1);var o=C(r,"x","cumsum"),a=Et([t|=0],o.rank),i=o;a!=null&&(i=o.transpose(a));var s=It(1,o.rank)[0],u=A.runKernelFunc((function(c){return c.cumsum(i,s,e,n)}),{permutedX:i},(function(c){return{permutedX:function(){return c.cumsum(t,e,!n)}}}));return a!=null&&(u=u.transpose(a)),u}}),Xc=D({depthToSpace_:function(r,t,e){e===void 0&&(e="NHWC");var n=C(r,"x","depthToSpace"),o=e==="NHWC"?n.shape[1]:n.shape[2],a=e==="NHWC"?n.shape[2]:n.shape[3],i=e==="NHWC"?n.shape[3]:n.shape[1];return E(o*t>=0,(function(){return`Negative dimension size caused by overflow when multiplying + `+o+" and "+t+` for depthToSpace with input shape + `+n.shape})),E(a*t>=0,(function(){return`Negative dimension size caused by overflow when multiplying + `+a+" and "+t+` for depthToSpace with input shape + `+n.shape})),E(i%(t*t)==0,(function(){return"Dimension size must be evenly divisible by "+t*t+" but is "+i+" for depthToSpace with input shape "+n.shape})),A.runKernelFunc((function(s){return s.depthToSpace(n,t,e)}),{$x:n})}}),st=D({expandDims_:function(r,t){t===void 0&&(t=0);var e=C(r,"x","expandDims",null);E(t<=e.rank,(function(){return"Axis must be <= rank of the tensor"}));var n=e.shape.slice();return t<0&&(E(-(e.rank+1)<=t,(function(){return"Axis must be in the interval ["+-(e.rank+1)+", "+e.rank+"]"})),t=e.rank+t+1),n.splice(t,0,1),mt(e,n)}}),Ci=D({eye_:function(r,t,e,n){n===void 0&&(n="float32"),t==null&&(t=r);for(var o=re([r,t],n),a=r<=t?r:t,i=0;i2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);e=e||Math.random();var s=i===1?o.as2D(1,-1):o,u=A.runKernelFunc((function(c){return c.multinomial(s,n,t,e)}),{logits2D:s});return i===1?u.as1D():u}}),bo=D({oneHot_:function(r,t,e,n){if(e===void 0&&(e=1),n===void 0&&(n=0),t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);var o=C(r,"indices","oneHot","int32"),a=o.shape.concat([t]);return o=o.flatten(),A.runKernelFunc((function(i){return i.oneHot(o,t,e,n)}),{$indices:o},(function(i){return{$indices:function(){return Ce(o.shape,"float32")}}})).reshape(a)}}),vn=D({pad_:function(r,t,e){e===void 0&&(e=0);var n=C(r,"x","pad");if(n.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var o={paddings:t,constantValue:e};return A.runKernelFunc((function(a){return a.pad(n,t,e)}),{x:n},(function(a){var i=t.map((function(s){return s[0]}));return{x:function(){return a.slice(i,n.shape)}}}),"PadV2",o)}}),$c=D({pad1d_:function(r,t,e){return e===void 0&&(e=0),E(t.length===2,(function(){return"Invalid number of paddings. Must be length of 2."})),vn(r,[t],e)}}),Jc=D({pad2d_:function(r,t,e){return e===void 0&&(e=0),E(t.length===2&&t[0].length===2&&t[1].length===2,(function(){return"Invalid number of paddings. Must be length of 2 each."})),vn(r,t,e)}}),Qc=D({pad3d_:function(r,t,e){return e===void 0&&(e=0),E(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,(function(){return"Invalid number of paddings. Must be length of 2 each."})),vn(r,t,e)}}),Zc=D({pad4d_:function(r,t,e){return e===void 0&&(e=0),E(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,(function(){return"Invalid number of paddings. Must be length of 2 each."})),vn(r,t,e)}}),el=D({rand_:function(r,t,e){var n=Z(r),o=null;if(e==null||e==="float32")o=new Float32Array(n);else if(e==="int32")o=new Int32Array(n);else{if(e!=="bool")throw new Error("Unknown data type "+e);o=new Uint8Array(n)}for(var a=0;a=1+t.length,(function(){return"input rank "+n.rank+" should be > than [blockShape] "+t.length})),E(e.length===t.length,(function(){return"paddings.shape[0] "+e.length+" must be equal to [blockShape] "+t.length})),E(n.shape.reduce((function(o,a,i){return i>0&&i<=t.length?o&&(a+e[i-1][0]+e[i-1][1])%t[i-1]==0:o}),!0),(function(){return"input spatial dimensions "+n.shape.slice(1)+" with paddings "+e.toString()+" must be divisible by blockShapes "+t.toString()})),A.runKernelFunc((function(o){return o.spaceToBatchND(n,t,e)}),{$x:n},(function(o){return{$x:function(){return o.batchToSpaceND(t,e)}}}))}}),Ii=D({squeeze_:function(r,t){var e=C(r,"x","squeeze");return mt(e,sn(e.shape,t).newShape)}}),ot=D({stack_:function(r,t){t===void 0&&(t=0);var e=Rr(r,"tensors","stack");if(E(e.length>=1,(function(){return"Pass at least one tensor to tf.stack"})),e.length===1)return e[0].expandDims(t);var n=e[0].rank,o=e[0].shape,a=e[0].dtype;E(t<=n,(function(){return"Axis must be <= rank of the tensor"})),e.forEach((function(s){me(o,s.shape,"All tensors passed to stack must have matching shapes")})),e.forEach((function(s){E(a===s.dtype,(function(){return"All tensors passed to stack must have matching dtypes"}))}));var i=e.map((function(s){return s.expandDims(t)}));return Pe(i,t)}}),kn=D({tile_:function(r,t){var e=C(r,"x","tile",null);E(e.rank===t.length,(function(){return"Error in transpose: rank of input "+e.rank+" must match length of reps "+t+"."}));var n=[e],o={reps:t};return A.runKernelFunc((function(a,i){var s=a.tile(e,t);return i([e]),s}),{x:e},(function(a,i){var s=i[0];return{x:function(){var u=de(s);if(s.rank===1)for(var c=0;c=-e.shape.length&&t=2*t+1||o%2==1?i.push(o):a.push(o);n.push.apply(n,a),n.push(0),n.push.apply(n,i)}return n}function _o(r,t,e,n){n===void 0&&(n=!0);var o=[];n?o.push(r[0]/e):o.push(r[0]*e);for(var a=1;ar.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+t.shape[t.rank-1]+" vs. "+r.rank);if(r.size===0)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+r.shape+".");for(var e=t.shape,n=e[e.length-1],o=1,a=0;a1?t.shape[t.rank-1]:1,o=t.rank>1?t.rank-1:1,a="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+e.shape+", indices.shape: "+t.shape+", shape: "+r+", sliceDim: "+n+", and batchDim: "+o+".";if(e.rank1?t.shape[n-1]:1,a=e.length,i=1,s=o;s0;)1&r&&t.push(e),r/=2,e++;return t}function Oo(r,t,e){for(var n=[],o=0;o0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=n[o];return a<0&&(a+=s),a=mo(0,a,s-1)}function hl(r,t,e,n,o){var a=t[o],i=e[o]||1;(r&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=n[o];return a<0&&(a+=s),a=i>0?mo(0,a,s):mo(-1,a,s-1)}function Si(r,t,e){for(var n=e.length,o=0;o1){n=o;break}for(o=n+1;o0||e[o]!==r[o])return!1;return!0}function Ai(r,t){for(var e=r.length>0?r[r.length-1]:1,n=0;n0,(function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+a+" variables is trainable."}));var i=A.gradients(r,t,null,!0),s=i.value,u=i.grads;E(u.some((function(l){return l!=null})),(function(){return"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()."})),E(s.rank===0,(function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"}));var c={};return t.forEach((function(l,h){u[h]!=null&&(c[l.name]=u[h])})),o?.forEach((function(l){return c[l.name]=null})),{value:s,grads:c}}function Wr(r){return A.customGrad(r)}function Bo(r){if(r.filter((function(t){return t==null})).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.`)}var Lt=D({softmax_:function(r,t){t===void 0&&(t=-1);var e=C(r,"logits","softmax","float32");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+e.rank+" and dim was "+t);return A.runKernelFunc((function(n,o){var a=n.softmax(e,t);return o([a]),a}),{logits:e},(function(n,o){var a=o[0],i=n.mul(a);return{logits:function(){return i.sub(i.sum([t],!0).mul(a))}}}),"Softmax",{dim:t},[],[!0])}}),dl=D({logSoftmax_:function(r,t){t===void 0&&(t=-1);var e=C(r,"logits","logSoftmax");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+e.rank+" and axis was "+t);return Wr((function(n,o){var a=n.max(t,!0),i=n.sub(a),s=i.toFloat().sub(i.exp().sum(t,!0).log());return o([s]),{value:s,gradFunc:function(u,c){var l=c[0].exp();return u.sub(u.sum(t,!0).mul(l))}}}))(e)}}),Di=(function(){function r(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}return r.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)},r.prototype.set=function(t,e){this.dataIdsCount++,this.data.set(t,e)},r.prototype.has=function(t){return this.data.has(t)},r.prototype.delete=function(t){return this.dataIdsCount--,this.data.delete(t)},r.prototype.numDataIds=function(){return this.dataIdsCount},r})(),Ti=(function(){function r(){}return r.prototype.time=function(t){return N("time")},r.prototype.read=function(t){return N("read")},r.prototype.readSync=function(t){return N("readSync")},r.prototype.numDataIds=function(){return N("numDataIds")},r.prototype.disposeData=function(t){return N("disposeData")},r.prototype.write=function(t,e,n){return N("write")},r.prototype.move=function(t,e,n,o){return N("move")},r.prototype.memory=function(){return N("memory")},r.prototype.floatPrecision=function(){return N("floatPrecision")},r.prototype.epsilon=function(){return this.floatPrecision()===32?1e-7:1e-4},r.prototype.batchMatMul=function(t,e,n,o){return N("batchMatMul")},r.prototype.fusedBatchMatMul=function(t){return t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights,N("fusedBatchMatMul")},r.prototype.slice=function(t,e,n){return N("slice")},r.prototype.stridedSlice=function(t,e,n,o){return N("stridedSlice")},r.prototype.unstack=function(t,e){return N("unstack")},r.prototype.reverse=function(t,e){return N("reverse")},r.prototype.concat=function(t,e){return N("concat")},r.prototype.neg=function(t){return N("neg")},r.prototype.add=function(t,e){return N("add")},r.prototype.addN=function(t){return N("addN")},r.prototype.subtract=function(t,e){return N("subtract")},r.prototype.multiply=function(t,e){return N("multiply")},r.prototype.realDivide=function(t,e){return N("realDivide")},r.prototype.floorDiv=function(t,e){return N("floorDiv")},r.prototype.sum=function(t,e){return N("sum")},r.prototype.prod=function(t,e){return N("prod")},r.prototype.unsortedSegmentSum=function(t,e,n){return N("unsortedSegmentSum")},r.prototype.argMin=function(t,e){return N("argMin")},r.prototype.argMax=function(t,e){return N("argMax")},r.prototype.equal=function(t,e){return N("equal")},r.prototype.notEqual=function(t,e){return N("notEqual")},r.prototype.less=function(t,e){return N("less")},r.prototype.lessEqual=function(t,e){return N("lessEqual")},r.prototype.greater=function(t,e){return N("greater")},r.prototype.greaterEqual=function(t,e){return N("greaterEqual")},r.prototype.logicalNot=function(t){return N("logicalNot")},r.prototype.logicalAnd=function(t,e){return N("logicalAnd")},r.prototype.logicalOr=function(t,e){return N("logicalOr")},r.prototype.where=function(t){return N("where")},r.prototype.select=function(t,e,n){return N("select")},r.prototype.topk=function(t,e,n){return N("topk")},r.prototype.min=function(t,e){return N("min")},r.prototype.minimum=function(t,e){return N("minimum")},r.prototype.mod=function(t,e){return N("mod")},r.prototype.max=function(t,e){return N("max")},r.prototype.maximum=function(t,e){return N("maximum")},r.prototype.all=function(t,e){return N("all")},r.prototype.any=function(t,e){return N("any")},r.prototype.squaredDifference=function(t,e){return N("squaredDifference")},r.prototype.ceil=function(t){return N("ceil")},r.prototype.floor=function(t){return N("floor")},r.prototype.round=function(t){return N("round")},r.prototype.sign=function(t){return N("sign")},r.prototype.isNaN=function(t){return N("isNaN")},r.prototype.isInf=function(t){return N("isInf")},r.prototype.isFinite=function(t){return N("isFinite")},r.prototype.pow=function(t,e){return N("pow")},r.prototype.exp=function(t){return N("exp")},r.prototype.expm1=function(t){return N("expm1")},r.prototype.softmax=function(t,e){return N("softmax")},r.prototype.log=function(t){return N("log")},r.prototype.log1p=function(t){return N("log1p")},r.prototype.sqrt=function(t){return N("sqrt")},r.prototype.rsqrt=function(t){return N("rsqrt")},r.prototype.square=function(t){return N("square")},r.prototype.reciprocal=function(t){return N("reciprocal")},r.prototype.relu=function(t){return N("relu")},r.prototype.relu6=function(t){return N("relu6")},r.prototype.prelu=function(t,e){return N("prelu")},r.prototype.elu=function(t){return N("elu")},r.prototype.eluDer=function(t,e){return N("eluDer")},r.prototype.selu=function(t){return N("selu")},r.prototype.int=function(t){return N("int")},r.prototype.clip=function(t,e,n){return N("clip")},r.prototype.abs=function(t){return N("abs")},r.prototype.complexAbs=function(t){return N("complexAbs")},r.prototype.sigmoid=function(t){return N("sigmoid")},r.prototype.softplus=function(t){return N("softplus")},r.prototype.sin=function(t){return N("sin")},r.prototype.cos=function(t){return N("cos")},r.prototype.tan=function(t){return N("tan")},r.prototype.asin=function(t){return N("asin")},r.prototype.acos=function(t){return N("acos")},r.prototype.atan=function(t){return N("atan")},r.prototype.atan2=function(t,e){return N("atan2")},r.prototype.sinh=function(t){return N("sinh")},r.prototype.cosh=function(t){return N("cosh")},r.prototype.tanh=function(t){return N("tanh")},r.prototype.asinh=function(t){return N("asinh")},r.prototype.acosh=function(t){return N("acosh")},r.prototype.atanh=function(t){return N("atanh")},r.prototype.erf=function(t){return N("erf")},r.prototype.step=function(t,e){return N("step")},r.prototype.fusedConv2d=function(t){return t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,N("fusedConv2d")},r.prototype.conv2d=function(t,e,n){return N("conv2d")},r.prototype.conv2dDerInput=function(t,e,n){return N("conv2dDerInput")},r.prototype.conv2dDerFilter=function(t,e,n){return N("conv2dDerFilter")},r.prototype.fusedDepthwiseConv2D=function(t){return t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,N("fusedDepthwiseConv2D")},r.prototype.depthwiseConv2D=function(t,e,n){return N("depthwiseConv2D")},r.prototype.depthwiseConv2DDerInput=function(t,e,n){return N("depthwiseConv2DDerInput")},r.prototype.depthwiseConv2DDerFilter=function(t,e,n){return N("depthwiseConv2DDerFilter")},r.prototype.conv3d=function(t,e,n){return N("conv3d")},r.prototype.conv3dDerInput=function(t,e,n){return N("conv3dDerInput")},r.prototype.conv3dDerFilter=function(t,e,n){return N("conv3dDerFilter")},r.prototype.maxPool=function(t,e){return N("maxPool")},r.prototype.maxPoolBackprop=function(t,e,n,o){return N("maxPoolBackprop")},r.prototype.avgPool=function(t,e){return N("avgPool")},r.prototype.avgPoolBackprop=function(t,e,n){return N("avgPoolBackprop")},r.prototype.avgPool3d=function(t,e){return N("avgPool3d")},r.prototype.avgPool3dBackprop=function(t,e,n){return N("avgPool3dBackprop")},r.prototype.maxPool3d=function(t,e){return N("maxPool3d")},r.prototype.maxPool3dBackprop=function(t,e,n,o){return N("maxPool3dBackprop")},r.prototype.reshape=function(t,e){return N("reshape")},r.prototype.cast=function(t,e){return N("cast")},r.prototype.tile=function(t,e){return N("tile")},r.prototype.pad=function(t,e,n){return N("pad")},r.prototype.transpose=function(t,e){return N("transpose")},r.prototype.gather=function(t,e,n){return N("gather")},r.prototype.gatherND=function(t,e){return N("gatherND")},r.prototype.scatterND=function(t,e,n){return N("scatterND")},r.prototype.batchToSpaceND=function(t,e,n){return N("batchToSpaceND")},r.prototype.spaceToBatchND=function(t,e,n){return N("spaceToBatchND")},r.prototype.resizeBilinear=function(t,e,n,o){return N("resizeBilinear")},r.prototype.resizeBilinearBackprop=function(t,e,n){return N("resizeBilinearBackprop")},r.prototype.resizeNearestNeighbor=function(t,e,n,o){return N("resizeNearestNeighbor")},r.prototype.resizeNearestNeighborBackprop=function(t,e,n){return N("resizeNearestNeighborBackprop")},r.prototype.batchNormalization=function(t,e,n,o,a,i){return N("batchNormalization")},r.prototype.localResponseNormalization4D=function(t,e,n,o,a){return N("localResponseNormalization4D")},r.prototype.LRNGrad=function(t,e,n,o,a,i,s){return N("LRNGrad")},r.prototype.multinomial=function(t,e,n,o){return N("multinomial")},r.prototype.oneHot=function(t,e,n,o){return N("oneHot")},r.prototype.cumsum=function(t,e,n,o){return N("cumsum")},r.prototype.nonMaxSuppression=function(t,e,n,o,a){return N("nonMaxSuppression")},r.prototype.fft=function(t){return N("fft")},r.prototype.ifft=function(t){return N("ifft")},r.prototype.complex=function(t,e){return N("complex")},r.prototype.real=function(t){return N("real")},r.prototype.imag=function(t){return N("imag")},r.prototype.cropAndResize=function(t,e,n,o,a,i){return N("cropAndResize")},r.prototype.depthToSpace=function(t,e,n){return N("depthToSpace")},r.prototype.split=function(t,e,n){return N("split")},r.prototype.sparseToDense=function(t,e,n,o){return N("sparseToDense")},r.prototype.diag=function(t){return N("diag")},r.prototype.fill=function(t,e,n){return N("fill")},r.prototype.onesLike=function(t){return N("onesLike")},r.prototype.zerosLike=function(t){return N("zerosLike")},r.prototype.linspace=function(t,e,n){return N("linspace")},r.prototype.dispose=function(){return N("dispose")},r})();function N(r){throw new Error("'"+r+"' not yet implemented or not found in the registry. Did you forget to import the kernel?")}function qt(r,t){for(var e=r.length,n=[],o=0;o1&&i===1&&n.unshift(a)}return n}function Oe(r,t){for(var e=[],n=0;n1)&&e.unshift(a)}return e}function ce(r,t){for(var e=[],n=Math.max(r.length,t.length),o=0;o>>1)]);m>0?h=d+1:(f=d,p=!m)}return p?h:-h-1})(a,i,s||ov)})(r,t,e),o=n<0?-(n+1):n;r.splice(o,0,t)}function ov(r,t){return r>t?1:ro})).sort(ou),c=a>0?-.5/a:0,l=[],h=[];l.length0;){var f=u.pop(),d=f.score,p=f.boxIndex,m=f.suppressBeginIndex;if(d=m;--g){var x=av(r,p,l[g]);if(x>=n){v=!0;break}if(f.score=f.score*iv(n,c,x),f.score<=o)break}f.suppressBeginIndex=l.length,v||(f.score===d?(l.push(p),h.push(f.score)):f.score>o&&rv(u,f,ou))}var b=l.length;return s&&(l.fill(0,b),h.fill(0,b)),{selectedIndices:Fe(l,"int32"),selectedScores:Fe(h,"float32"),numValidOutputs:q(b,"int32")}}function av(r,t,e){var n=r.subarray(4*t,4*t+4),o=r.subarray(4*e,4*e+4),a=Math.min(n[0],n[2]),i=Math.min(n[1],n[3]),s=Math.max(n[0],n[2]),u=Math.max(n[1],n[3]),c=Math.min(o[0],o[2]),l=Math.min(o[1],o[3]),h=Math.max(o[0],o[2]),f=Math.max(o[1],o[3]),d=(s-a)*(u-i),p=(h-c)*(f-l);if(d<=0||p<=0)return 0;var m=Math.max(a,c),v=Math.max(i,l),g=Math.min(s,h),x=Math.min(u,f),b=Math.max(g-m,0)*Math.max(x-v,0);return b/(d+p-b)}function iv(r,t,e){var n=Math.exp(t*e*e);return e<=r?n:0}function ou(r,t){return r.score-t.score||r.score===t.score&&t.boxIndex-r.boxIndex}function vl(r,t,e){var n=new Array(r.rank).fill(0),o=r.shape.slice();return t.map((function(a){o[e]=a;var i=r.slice(n,o);return n[e]+=a,i}))}function ml(r,t){for(var e=new Array(r.rank),n=0;n":"<",u=e?"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 * `+n+`; + + int bestIndex = inOffset; + float bestValue = getA(batch, bestIndex); + + for (int i = 0; i < `+n+`; i++) { + int inIdx = `+u+`; + float candidate = getA(batch, inIdx); + if (candidate `+s+` bestValue) { + bestValue = candidate; + bestIndex = inIdx; + } + } + setOutput(float(bestIndex)); + } + `};function yl(r,t){return["x","y","z","w","u","v"].slice(0,t).map((function(e){return r+"."+e}))}function rt(r,t){return t===1?[r]:yl(r,t)}function Je(){var r,t,e,n,o,a,i,s,u,c;return M().getNumber("WEBGL_VERSION")===2?(r="#version 300 es",t="in",e="out",n="in",o="texture",a="outputColor",i="out vec4 outputColor;",s=` + bool isnan_custom(float val) { + return (val > 0.0 || val < 0.0) ? false : val != 0.0; + } + + 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) + `,u="",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))); + } + `):(r="",t="attribute",e="varying",n="varying",o="texture2D",a="gl_FragColor",i="",s=` + #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)); + } + `,u=` + 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:r,attribute:t,varyingVs:e,varyingFs:n,texture2D:o,output:a,defineOutput:i,defineSpecialNaN:s,defineSpecialInf:u,defineRound:c}}function En(r,t,e){e===void 0&&(e="index");var n=xt(t);return n.map((function(o,a){return"int "+r[a]+" = "+e+" / "+o+"; "+(a===n.length-1?"int "+r[a+1]+" = "+e+" - "+r[a]+" * "+o:"index -= "+r[a]+" * "+o)+";"})).join("")}function Li(r){var t=xt(r).map((function(e){return e.toString()}));return` + int getFlatIndex(ivec3 coords) { + return coords.x * `+t[0]+" + coords.y * "+t[1]+` + coords.z; + } +`}var xl=` + 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; + } +`;function lv(r,t,e,n){var o=[];r.forEach((function(d){var p=Z(d.shapeInfo.logicalShape);d.shapeInfo.isUniform?o.push("uniform float "+d.name+(p>1?"["+p+"]":"")+";"):(o.push("uniform sampler2D "+d.name+";"),o.push("uniform int offset"+d.name+";"))}));var a,i,s=o.join(` +`),u=r.map((function(d){return(function(p,m,v){v===void 0&&(v=!1);var g="";g+=v?bl(p):Vn(p);var x=p.shapeInfo.logicalShape,b=m.logicalShape;return x.length<=b.length&&(g+=v?(function(y,w){var _,S=y.name,k=S.charAt(0).toUpperCase()+S.slice(1),I="get"+k+"AtOutCoords",R=y.shapeInfo.logicalShape.length,F=w.logicalShape.length,T=qt(y.shapeInfo.logicalShape,w.logicalShape),L=_e(F),O=F-R,B=["x","y","z","w","u","v"];_=R===0?"":F<2&&T.length>=1?"coords = 0;":T.map((function(ee){return"coords."+B[ee+O]+" = 0;"})).join(` +`);var U="";U=F<2&&R>0?"coords":y.shapeInfo.logicalShape.map((function(ee,te){return"coords."+B[te+O]})).join(", ");var z="return outputValue;",W=Z(y.shapeInfo.logicalShape)===1,G=Z(w.logicalShape)===1;if(R!==1||W||G){if(W&&!G)z=F===1?` + return vec4(outputValue.x, outputValue.x, 0., 0.); + `:` + return vec4(outputValue.x); + `;else if(T.length){var H=R-2,j=R-1;T.indexOf(H)>-1&&T.indexOf(j)>-1?z="return vec4(outputValue.x);":T.indexOf(H)>-1?z="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":T.indexOf(j)>-1&&(z="return vec4(outputValue.xx, outputValue.zz);")}}else z=` + return vec4(outputValue.xy, outputValue.xy); + `;return` + vec4 `+I+`() { + `+L+` coords = getOutputCoords(); + `+_+` + vec4 outputValue = get`+k+"("+U+`); + `+z+` + } + `})(p,m):(function(y,w){var _=y.name,S=_.charAt(0).toUpperCase()+_.slice(1),k="get"+S+"AtOutCoords",I=w.texShape,R=y.shapeInfo.texShape,F=y.shapeInfo.logicalShape.length,T=w.logicalShape.length;if(!y.shapeInfo.isUniform&&F===T&&y.shapeInfo.flatOffset==null&&Ne(R,I))return` + float `+k+`() { + return sampleTexture(`+_+`, resultUV); + } + `;var L,O=_e(T),B=qt(y.shapeInfo.logicalShape,w.logicalShape),U=T-F,z=["x","y","z","w","u","v"];L=F===0?"":T<2&&B.length>=1?"coords = 0;":B.map((function(G){return"coords."+z[G+U]+" = 0;"})).join(` +`);var W="";return W=T<2&&F>0?"coords":y.shapeInfo.logicalShape.map((function(G,H){return"coords."+z[H+U]})).join(", "),` + float `+k+`() { + `+O+` coords = getOutputCoords(); + `+L+` + return get`+S+"("+W+`); + } + `})(p,m)),g})(d,t,n)})).join(` +`),c=t.texShape,l=Je(),h=(function(d){return` + float sampleTexture(sampler2D textureSampler, vec2 uv) { + return `+d.texture2D+`(textureSampler, uv).r; + } + `})(l),f=(function(d){return d.version+` + precision highp float; + precision highp int; + precision highp sampler2D; + `+d.varyingFs+` vec2 resultUV; + `+d.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; + `+d.defineSpecialNaN+` + `+d.defineSpecialInf+` + `+d.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); + } + + `+hv+` + `+fv+` + `+dv+` + `})(l);return t.isPacked?(a=(function(d,p){switch(d.length){case 0:return` + int getOutputCoords() { + return 0; + } + `;case 1:return(function(y,w){var _=[Math.ceil(w[0]/2),Math.ceil(w[1]/2)];return _[0]===1?` + int getOutputCoords() { + return 2 * int(resultUV.x * `+_[1]+`.0); + } + `:_[1]===1?` + int getOutputCoords() { + return 2 * int(resultUV.y * `+_[0]+`.0); + } + `:` + int getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(`+_[0]+", "+_[1]+`)); + return 2 * (resTexRC.x * `+_[1]+` + resTexRC.y); + } + `})(0,p);case 2:return(function(y,w){var _=[Math.ceil(w[0]/2),Math.ceil(w[1]/2)];if(Ne(y,w))return` + ivec2 getOutputCoords() { + return 2 * ivec2(resultUV.yx * vec2(`+_[0]+", "+_[1]+`)); + } + `;var S=Math.ceil(y[1]/2);return` + ivec2 getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(`+_[0]+", "+_[1]+`)); + + int index = resTexRC.x * `+_[1]+` + resTexRC.y; + int r = 2 * (index / `+S+`); + int c = imod(index, `+S+`) * 2; + + return ivec2(r, c); + } + `})(d,p);case 3:return m=d,v=p,g=[Math.ceil(v[0]/2),Math.ceil(v[1]/2)],x=Math.ceil(m[2]/2),b=x*Math.ceil(m[1]/2),` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(`+g[0]+", "+g[1]+`)); + int index = resTexRC.x * `+g[1]+` + resTexRC.y; + + int b = index / `+b+`; + index -= b * `+b+`; + + int r = 2 * (index / `+x+`); + int c = imod(index, `+x+`) * 2; + + return ivec3(b, r, c); + } + `;default:return(function(y,w){for(var _=[Math.ceil(w[0]/2),Math.ceil(w[1]/2)],S=Math.ceil(y[y.length-1]/2),k=S*Math.ceil(y[y.length-2]/2),I=k,R="",F="b, r, c",T=2;T2,(function(){return"Packed arg"+(e.charAt(0).toUpperCase()+e.slice(1))+" supports only inputs with rank above 2."}));var o=r[r.length-1],a=Math.ceil(o/t);this.outputShape=r.slice(0,-1),a>1&&this.outputShape.push(a),n||this.variableNames.push("bestIndicesA");var i,s,u=this.outputShape,c=u.length,l=_e(c),h=rt("coords",c);if(a===1){var f=_e(s=c+1);i=` + `+f+" sourceLocR = "+f+"("+h.join()+`, 0); + ++`+h[c-1]+`; + `+f+" sourceLocG = "+f+"("+h.join()+`, 0); + ++`+h[c-2]+`; + `+f+" sourceLocA = "+f+"("+h.join()+`, 0); + --`+h[c-1]+`; + `+f+" sourceLocB = "+f+"("+h.join()+`, 0); + --`+h[c-2]+";"}else s=c,i=` + `+l+` sourceLocR = coords; + ++`+h[c-1]+`; + `+l+` sourceLocG = coords; + ++`+h[c-2]+`; + `+l+` sourceLocA = coords; + --`+h[c-1]+`; + `+l+` sourceLocB = coords; + --`+h[c-2]+";";var d=["x","y","z","w","u","v"].slice(0,s),p="."+d[s-1],m=d.map((function(k){return"int "+k})),v=rt("sourceLocR",s-1).concat("inIdx.r"),g=rt("sourceLocG",s-1).concat("inIdx.g"),x=rt("sourceLocB",s-1).concat("inIdx.b"),b=rt("sourceLocA",s-1).concat("inIdx.a"),y=e==="max"?"greaterThan":"lessThan",w=n?"":` + inIdx = round(vec4(getBestIndicesAChannel(`+v.join()+`), + getBestIndicesAChannel(`+g.join()+`), + getBestIndicesAChannel(`+x.join()+`), + getBestIndicesAChannel(`+b.join()+")));",_=`vec4( + getAChannel(`+v.join()+`), + hasNextCol ? getAChannel(`+g.join()+`) : 0., + hasNextRow ? getAChannel(`+x.join()+`) : 0., + hasNextRow && hasNextCol ? getAChannel(`+b.join()+") : 0.)",S=n?"":` + float getBestIndicesAChannel(`+m.join()+`) { + return getChannel(getBestIndicesA(`+d.join()+`), + vec2(`+d.slice(-2).join()+`)); + }`;this.userCode=` + float getAChannel(`+m.join()+`) { + return getChannel(getA(`+d.join()+`), + vec2(`+d.slice(-2).join()+`)); + } + `+S+` + void main() { + `+l+` coords = getOutputCoords(); + bool hasNextCol = `+h[c-1]+" < "+(u[c-1]-1)+`; + bool hasNextRow = `+h[c-2]+" < "+(u[c-2]-1)+`; + `+i+` + ivec4 srcIdx = ivec4(sourceLocR`+p+", sourceLocG"+p+`, + sourceLocB`+p+", sourceLocA"+p+") * "+t+`; + ivec4 inIdx = srcIdx; + vec4 bestIndex = vec4(inIdx); + vec4 bestValue = `+_+`; + + for (int i = 0; i < `+t+`; i++) { + inIdx = srcIdx; + `+w+` + vec4 candidate = `+_+`; + 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); + } + `},mv=function(r){this.variableNames=["dy"],this.outputShape=r.inShape;var t=r.filterHeight,e=r.filterWidth,n=r.strideHeight,o=r.strideWidth,a=r.dilationHeight,i=r.dilationWidth,s=r.effectiveFilterHeight,u=r.effectiveFilterWidth,c=s-1-r.padInfo.top,l=u-1-r.padInfo.left,h=1/(t*e);this.userCode=` + const ivec2 pads = ivec2(`+c+", "+l+`); + const float avgMultiplier = float(`+h+`); + + 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 < `+s+`; + wR += `+a+`) { + float dyR = float(dyRCorner + wR) / `+n+`.0; + + if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < `+u+`; + wC+= `+i+`) { + float dyC = float(dyCCorner + wC) / `+o+`.0; + + if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(b, idyR, idyC, d); + + dotProd += dyValue * avgMultiplier; + } + } + setOutput(dotProd); + } + `},gv=function(r){this.variableNames=["dy"],this.outputShape=r.inShape;var t=r.filterDepth,e=r.filterHeight,n=r.filterWidth,o=r.strideDepth,a=r.strideHeight,i=r.strideWidth,s=r.dilationDepth,u=r.dilationHeight,c=r.dilationWidth,l=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,d=l-1-r.padInfo.front,p=h-1-r.padInfo.top,m=f-1-r.padInfo.left,v=1/(t*e*n);this.userCode=` + const ivec3 pads = ivec3(`+d+", "+p+", "+m+`); + const float avgMultiplier = float(`+v+`); + + 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 < `+l+`; + wD += `+s+`) { + float dyD = float(dyDCorner + wD) / `+o+`.0; + + if (dyD < 0.0 || dyD >= `+r.outDepth+`.0 || fract(dyD) > 0.0) { + continue; + } + int idyD = int(dyD); + + for (int wR = 0; wR < `+h+`; + wR += `+u+`) { + float dyR = float(dyRCorner + wR) / `+a+`.0; + + if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < `+f+`; + wC += `+c+`) { + float dyC = float(dyCCorner + wC) / `+i+`.0; + + if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(batch, idyD, idyR, idyC, ch); + + dotProd += dyValue * avgMultiplier; + } + } + } + setOutput(dotProd); + } + `},yv=function(r,t,e,n,o,a){this.outputShape=[],this.variableNames=["x","mean","variance"],ce(r,t),ce(r,e);var i="0.0";n!=null&&(ce(r,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";o!=null&&(ce(r,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=r,this.userCode=` + void main() { + float x = getXAtOutCoords(); + float mean = getMeanAtOutCoords(); + float variance = getVarianceAtOutCoords(); + float offset = `+i+`; + float scale = `+s+`; + float inv = scale * inversesqrt(variance + float(`+a+`)); + setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1))); + } + `},xv=function(r,t,e,n,o,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],ce(r,t),ce(r,e);var i="vec4(0.0)";n!=null&&(ce(r,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="vec4(1.0)";o!=null&&(ce(r,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=r,this.userCode=` + void main() { + vec4 offset = `+i+`; + vec4 scale = `+s+`; + + vec4 x = getXAtOutCoords(); + vec4 mean = getMeanAtOutCoords(); + vec4 variance = getVarianceAtOutCoords(); + + vec4 inv = scale * inversesqrt(variance + vec4(`+a+`)); + + setOutput((x - mean) * inv + offset); + } + `},bv="return areal * breal - aimag * bimag;",wv="return areal * bimag + aimag * breal;",au=function(r,t,e){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=ce(t,e),this.userCode=` + float binaryOpComplex( + float areal, float aimag, float breal, float bimag) { + `+r+` + } + + void main() { + float areal = getARealAtOutCoords(); + float aimag = getAImagAtOutCoords(); + float breal = getBRealAtOutCoords(); + float bimag = getBImagAtOutCoords(); + setOutput(binaryOpComplex(areal, aimag, breal, bimag)); + } + `},pa="return a + b;",va="return a - b;",iu="return a * b;",wl="return (a < 0.) ? b * a : a;",Ae=function(r,t,e){this.variableNames=["A","B"],this.outputShape=ce(t,e),this.userCode=` + float binaryOperation(float a, float b) { + `+r+` + } + + void main() { + float a = getAAtOutCoords(); + float b = getBAtOutCoords(); + setOutput(binaryOperation(a, b)); + } + `},Cl=` + vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); + return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); +`,Gt=function(r,t,e,n){n===void 0&&(n=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=ce(t,e);var o=this.outputShape.length,a="";if(n)if(o===0||Z(this.outputShape)===1)a=` + result.y = 0.; + result.z = 0.; + result.w = 0.; + `;else if(a=` + `+_e(o)+` coords = getOutputCoords(); + `,o===1)a+=` + result.y = (coords + 1) >= `+this.outputShape[0]+` ? 0. : result.y; + result.z = 0.; + result.w = 0.; + `;else{var i=rt("coords",o);a+=` + bool nextRowOutOfBounds = + (`+i[o-2]+" + 1) >= "+this.outputShape[o-2]+`; + bool nextColOutOfBounds = + (`+i[o-1]+" + 1) >= "+this.outputShape[o-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) { + `+r+` + } + + void main() { + vec4 a = getAAtOutCoords(); + vec4 b = getBAtOutCoords(); + + vec4 result = binaryOperation(a, b); + `+a+` + + setOutput(result); + } + `},Cv=(function(){function r(t){this.variableNames=["A"],this.outputShape=t,this.userCode=` + uniform float minVal; + uniform float maxVal; + + void main() { + float value = getAAtOutCoords(); + if (isnan(value)) { + setOutput(value); + return; + } + + setOutput(clamp(value, minVal, maxVal)); + } + `}return r.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(o,a){n.minLoc==null&&(n.minLoc=o.getUniformLocationNoThrow(a,"minVal"),n.maxLoc=o.getUniformLocationNoThrow(a,"maxVal")),o.gl.uniform1f(n.minLoc,t),o.gl.uniform1f(n.maxLoc,e)}},r})(),_v=(function(){function r(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode=` + uniform float minVal; + uniform float maxVal; + + void main() { + vec4 value = getAAtOutCoords(); + + if (any(isnan(value))) { + setOutput(value); + return; + } + + setOutput(clamp(value, vec4(minVal), vec4(maxVal))); + } + `}return r.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(o,a){n.minLoc==null&&(n.minLoc=o.getUniformLocationNoThrow(a,"minVal"),n.maxLoc=o.getUniformLocationNoThrow(a,"maxVal")),o.gl.uniform1f(n.minLoc,t),o.gl.uniform1f(n.maxLoc,e)}},r})(),Ev=function(r){this.variableNames=["real","imag"],this.outputShape=r,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)) + ); + } + `},Iv=function(r){this.outputShape=[],this.outputShape=Dn(r,1),this.variableNames=r.map((function(s,u){return"T"+u}));var t=new Array(r.length-1);t[0]=r[0][1];for(var e=1;e= "+s[u-1]+`) { + return getChannel( + getT`+u+"("+Jr(i,c,d)+`), + vec2(`+Jr(l,c,d)+`)); + }`}var p=s.length,m=s[s.length-1];f+=` + return getChannel( + getT`+p+"("+Jr(i,c,m)+`), + vec2(`+Jr(l,c,m)+"));",this.userCode=` + float getValue(`+i.map((function(v){return"int "+v}))+`) { + `+f+` + } + + void main() { + `+o+` coords = getOutputCoords(); + vec4 result = vec4(getValue(`+a+`), 0., 0., 0.); + + `+a[n-1]+" = "+a[n-1]+` + 1; + if (`+a[n-1]+" < "+e[n-1]+`) { + result.g = getValue(`+a+`); + } + + `+a[n-2]+" = "+a[n-2]+` + 1; + if (`+a[n-2]+" < "+e[n-2]+`) { + result.a = getValue(`+a+`); + } + + `+a[n-1]+" = "+a[n-1]+` - 1; + if (`+a[n-2]+" < "+e[n-2]+` && + `+a[n-1]+" < "+e[n-1]+`) { + result.b = getValue(`+a+`); + } + setOutput(result); + } + `};function Jr(r,t,e){var n=r.indexOf(t);return r.map((function(o,a){return a===n?o+" - "+e:o})).join()}var kv=function(r){this.variableNames=["x","dy"],this.outputShape=r.filterShape;var t=r.strideHeight,e=r.strideWidth,n=r.padInfo.top,o=r.padInfo.left,a=r.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 < `+r.batchSize+`; b++) { + for (int yR = 0; yR < `+r.outHeight+`; yR++) { + int xR = wR + yR * `+t+" - "+n+`; + + if (xR < 0 || xR >= `+r.inHeight+`) { + continue; + } + + for (int yC = 0; yC < `+r.outWidth+`; yC++) { + int xC = wC + yC * `+e+" - "+o+`; + + if (xC < 0 || xC >= `+r.inWidth+`) { + continue; + } + + if (`+a+`) { + float dyValue = getDy(b, yR, yC, d2); + float xValue = getX(b, xR, xC, d1); + dotProd += (xValue * dyValue); + } else { + float dyValue = getDy(b, d2, yR, yC); + float xValue = getX(b, d1, xR, xC); + dotProd += (xValue * dyValue); + } + + } + } + } + setOutput(dotProd); + } + `},Sv=function(r){this.variableNames=["dy","W"],this.outputShape=r.inShape;var t=r.filterHeight,e=r.filterWidth,n=r.strideHeight,o=r.strideWidth,a=r.dataFormat==="channelsLast",i=t-1-r.padInfo.top,s=e-1-r.padInfo.left,u=a?1:2,c=a?2:3,l=a?3:1;this.userCode=` + const ivec2 pads = ivec2(`+i+", "+s+`); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d1 = coords[`+l+`]; + + ivec2 dyCorner = ivec2(coords[`+u+"], coords["+c+`]) - 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) / `+n+`.0; + + if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = `+t+` - 1 - wR; + + for (int wC = 0; wC < `+e+`; wC++) { + float dyC = float(dyCCorner + wC) / `+o+`.0; + + if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = `+e+` - 1 - wC; + + for (int d2 = 0; d2 < `+r.outChannels+`; d2++) { + + if (`+a+`) { + 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); + } + `},Av=function(r){this.variableNames=["x","dy"],this.outputShape=r.filterShape;var t=r.strideDepth,e=r.strideHeight,n=r.strideWidth,o=r.padInfo.front,a=r.padInfo.top,i=r.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 < `+r.batchSize+`; b++) { + for (int yF = 0; yF < `+r.outDepth+`; yF++) { + int xF = wF + yF * `+t+" - "+o+`; + + if (xF < 0 || xF >= `+r.inDepth+`) { + continue; + } + + for (int yR = 0; yR < `+r.outHeight+`; yR++) { + int xR = wR + yR * `+e+" - "+a+`; + + if (xR < 0 || xR >= `+r.inHeight+`) { + continue; + } + + for (int yC = 0; yC < `+r.outWidth+`; yC++) { + int xC = wC + yC * `+n+" - "+i+`; + + if (xC < 0 || xC >= `+r.inWidth+`) { + continue; + } + + float dyValue = getDy(b, yF, yR, yC, d2); + float xValue = getX(b, xF, xR, xC, d1); + dotProd += (xValue * dyValue); + } + } + } + } + setOutput(dotProd); + } + `},Dv=function(r){this.variableNames=["dy","W"],this.outputShape=r.inShape;var t=r.filterDepth,e=r.filterHeight,n=r.filterWidth,o=r.strideDepth,a=r.strideHeight,i=r.strideWidth,s=t-1-r.padInfo.front,u=e-1-r.padInfo.top,c=n-1-r.padInfo.left;this.userCode=` + const ivec3 pads = ivec3(`+s+", "+u+", "+c+`); + + 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) / `+o+`.0; + + if (dyF < 0.0 || dyF >= `+r.outDepth+`.0 || fract(dyF) > 0.0) { + continue; + } + int idyF = int(dyF); + + int wFPerm = `+t+` - 1 - wF; + + for (int wR = 0; wR < `+e+`; wR++) { + float dyR = float(dyRCorner + wR) / `+a+`.0; + + if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = `+e+` - 1 - wR; + + for (int wC = 0; wC < `+n+`; wC++) { + float dyC = float(dyCCorner + wC) / `+i+`.0; + + if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = `+n+` - 1 - wC; + + for (int d2 = 0; d2 < `+r.outChannels+`; d2++) { + float xValue = getDy(batch, idyF, idyR, idyC, d2); + float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } + } + } + } + setOutput(dotProd); + } + `},Tv=function(r){this.variableNames=["x","dy"],this.outputShape=r.filterShape;var t=r.strideHeight,e=r.strideWidth,n=r.padInfo.top,o=r.padInfo.left,a=r.outChannels/r.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 * `+a+` + dm; + + float dotProd = 0.0; + + // TO DO: Vec4 over the batch size + for (int b = 0; b < `+r.batchSize+`; b++) { + for (int yR = 0; yR < `+r.outHeight+`; yR++) { + int xR = wR + yR * `+t+" - "+n+`; + + if (xR < 0 || xR >= `+r.inHeight+`) { + continue; + } + + for (int yC = 0; yC < `+r.outWidth+`; yC++) { + int xC = wC + yC * `+e+" - "+o+`; + + if (xC < 0 || xC >= `+r.inWidth+`) { + continue; + } + + float dyValue = getDy(b, yR, yC, d2); + float xValue = getX(b, xR, xC, d1); + dotProd += (xValue * dyValue); + } + } + } + setOutput(dotProd); + } + `},Fv=function(r){this.variableNames=["dy","W"],this.outputShape=r.inShape;var t=r.filterHeight,e=r.filterWidth,n=r.strideHeight,o=r.strideWidth,a=t-1-r.padInfo.top,i=e-1-r.padInfo.left,s=r.outChannels/r.inChannels;this.userCode=` + const ivec2 pads = ivec2(`+a+", "+i+`); + + 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) / `+n+`.0; + + if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = `+t+` - 1 - wR; + + for (int wC = 0; wC < `+e+`; wC++) { + float dyC = float(dyCCorner + wC) / `+o+`.0; + + if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = `+e+` - 1 - wC; + + // TO DO: Vec4 over the channelMul + for (int dm = 0; dm < `+s+`; dm++) { + int d2 = d1 * `+s+` + dm; + float xValue = getDy(batch, idyR, idyC, d2); + float wValue = getW(wRPerm, wCPerm, d1, dm); + dotProd += xValue * wValue; + } + } + } + setOutput(dotProd); + } + `},su=function(r,t,e,n){t===void 0&&(t=!1),e===void 0&&(e=null),n===void 0&&(n=!1),this.variableNames=["x","W"],this.outputShape=r.outShape;var o=r.padInfo.top,a=r.padInfo.left,i=r.strideHeight,s=r.strideWidth,u=r.dilationHeight,c=r.dilationWidth,l=r.filterHeight,h=r.filterWidth,f=4*Math.floor(r.inChannels/4),d=r.inChannels%4,p=r.dataFormat==="channelsLast",m=p?1:2,v=p?2:3,g=p?3:1,x="",b="";e&&(x=n?`float activation(float a) { + float b = getPreluActivationWeightsAtOutCoords(); + `+e+` + }`:` + float activation(float x) { + `+e+` + } + `,b="result = activation(result);");var y=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=` + `+x+` + + const ivec2 strides = ivec2(`+i+", "+s+`); + const ivec2 pads = ivec2(`+o+", "+a+`); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d2 = coords[`+g+`]; + + ivec2 xRCCorner = + ivec2(coords[`+m+"], 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 < `+l+`; wR++) { + int xR = xRCorner + wR * `+u+`; + + if (xR < 0 || xR >= `+r.inHeight+`) { + continue; + } + + for (int wC = 0; wC < `+h+`; wC++) { + int xC = xCCorner + wC * `+c+`; + + if (xC < 0 || xC >= `+r.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 (`+p+`) { + 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 (`+(d===1)+`) { + + if (`+p+`) { + 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 (`+(d===2)+`) { + vec2 wValues = vec2( + getW(wR, wC, `+f+`, d2), + getW(wR, wC, `+f+` + 1, d2) + ); + + if (`+p+`) { + 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 (`+(d===3)+`) { + vec3 wValues = vec3( + getW(wR, wC, `+f+`, d2), + getW(wR, wC, `+f+` + 1, d2), + getW(wR, wC, `+f+` + 2, d2) + ); + + if (`+p+`) { + 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; + `+y+` + `+b+` + setOutput(result); + } + `},Nv=function(r){this.variableNames=["x","W"],this.outputShape=r.outShape;var t=r.padInfo.front,e=r.padInfo.top,n=r.padInfo.left,o=r.strideDepth,a=r.strideHeight,i=r.strideWidth,s=r.dilationDepth,u=r.dilationHeight,c=r.dilationWidth,l=r.filterDepth,h=r.filterHeight,f=r.filterWidth,d=4*Math.floor(r.inChannels/4),p=r.inChannels%4;this.userCode=` + const ivec3 strides = ivec3(`+o+", "+a+", "+i+`); + const ivec3 pads = ivec3(`+t+", "+e+", "+n+`); + + 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 < `+l+`; wF++) { + int xF = xFCorner + wF * `+s+`; + + if (xF < 0 || xF >= `+r.inDepth+`) { + continue; + } + + for (int wR = 0; wR < `+h+`; wR++) { + int xR = xRCorner + wR * `+u+`; + + if (xR < 0 || xR >= `+r.inHeight+`) { + continue; + } + + for (int wC = 0; wC < `+f+`; wC++) { + int xC = xCCorner + wC * `+c+`; + + if (xC < 0 || xC >= `+r.inWidth+`) { + continue; + } + + for (int d1 = 0; d1 < `+d+`; 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 (`+(p===1)+`) { + dotProd += + getX(batch, xF, xR, xC, `+d+`) * + getW(wF, wR, wC, `+d+`, d2); + } else if (`+(p===2)+`) { + vec2 xValues = vec2( + getX(batch, xF, xR, xC, `+d+`), + getX(batch, xF, xR, xC, `+d+` + 1) + ); + vec2 wValues = vec2( + getW(wF, wR, wC, `+d+`, d2), + getW(wF, wR, wC, `+d+` + 1, d2) + ); + dotProd += dot(xValues, wValues); + } else if (`+(p===3)+`) { + vec3 xValues = vec3( + getX(batch, xF, xR, xC, `+d+`), + getX(batch, xF, xR, xC, `+d+` + 1), + getX(batch, xF, xR, xC, `+d+` + 2) + ); + vec3 wValues = vec3( + getW(wF, wR, wC, `+d+`, d2), + getW(wF, wR, wC, `+d+` + 1, d2), + getW(wF, wR, wC, `+d+` + 2, d2) + ); + dotProd += dot(xValues, wValues); + } + } + } + } + setOutput(dotProd); + } + `},uu=function(r,t,e,n){t===void 0&&(t=!1),e===void 0&&(e=null),n===void 0&&(n=!1),this.variableNames=["x","W"],this.outputShape=r.outShape;var o=r.inHeight,a=r.inWidth,i=r.padInfo.top,s=r.padInfo.left,u=r.strideHeight,c=r.strideWidth,l=r.dilationHeight,h=r.dilationWidth,f=r.filterHeight,d=r.filterWidth,p=r.outChannels/r.inChannels,m="",v="";e&&(m=n?`float activation(float a) { + float b = getPreluActivationWeightsAtOutCoords(); + `+e+` + }`:` + float activation(float x) { + `+e+` + } + `,v="result = activation(result);");var g=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=` + `+m+` + + const ivec2 strides = ivec2(`+u+", "+c+`); + const ivec2 pads = ivec2(`+i+", "+s+`); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + ivec2 xRCCorner = coords.yz * strides - pads; + int d2 = coords.w; + int d1 = d2 / `+p+`; + int q = d2 - d1 * `+p+`; + + 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 < `+f+`; wR++) { + int xR = xRCorner + wR * `+l+`; + + if (xR < 0 || xR >= `+o+`) { + continue; + } + + for (int wC = 0; wC < `+d+`; wC++) { + int xC = xCCorner + wC * `+h+`; + + if (xC < 0 || xC >= `+a+`) { + continue; + } + + float xVal = getX(batch, xR, xC, d1); + float wVal = getW(wR, wC, d1, q); + dotProd += xVal * wVal; + } + } + + float result = dotProd; + `+g+` + `+v+` + setOutput(result); + } + `},cu=function(r,t,e,n){t===void 0&&(t=!1),e===void 0&&(e=null),n===void 0&&(n=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r.outShape;for(var o=r.inHeight,a=r.inWidth,i=r.padInfo.top,s=r.padInfo.left,u=r.strideHeight,c=r.strideWidth,l=r.dilationHeight,h=r.dilationWidth,f=r.filterHeight,d=r.filterWidth,p=d,m="int xR; int xC; int xCOffset;",v=0;v= 0 && xR < `+o+" && xCOffset >= 0 && xCOffset < "+a+`) { + xTexelR`+v+"C"+g+` = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if(xCOffset + 1 >= `+a+`) { + xTexelR`+v+"C"+g+`.zw = vec2(0.); + } + } else { + xTexelR`+v+"C"+g+` = vec4(0.); + } + + xCOffset = xC + 1 - 2; + if(xR >= 0 && xR < `+o+" && xCOffset >= 0 && xCOffset < "+a+`) { + vec4 previous = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if(xCOffset + 1 >= `+a+`) { + previous.zw = vec2(0.); + } + + xR`+v+"C"+g+" = vec4(previous.zw, xTexelR"+v+"C"+g+`.xy); + } else { + xR`+v+"C"+g+" = vec4(0, 0, xTexelR"+v+"C"+g+`.xy); + } + `:` + if(xR >= 0 && xR < `+o+" && xC >= 0 && xC < "+a+`) { + xTexelR`+v+"C"+g+` = getX(batch, xR, xC, d1); + } else { + xTexelR`+v+"C"+g+` = vec4(0.); + } + + xR`+v+"C"+g+" = xTexelR"+v+"C"+g+`; + `,g+1= 0 && xR < `+o+` && + xCOffset >= 0 && xCOffset < `+a+`) { + xTexelR`+v+"C"+(g+2)+` = getX(batch, xR, xCOffset, d1); + } + `,h>1&&(m+=` + xCOffset -= 2; + if(xR >= 0 && xR < `+o+` && + xCOffset >= 0 && xCOffset < `+a+`) { + xTexelR`+v+"C"+g+` = getX(batch, xR, xCOffset, d1); + } else { + xTexelR`+v+"C"+g+` = vec4(0.); + } + `),m+=` + xR`+v+"C"+(g+1)+` = vec4( + xTexelR`+v+"C"+g+".zw, xTexelR"+v+"C"+(g+2)+`.xy); + `):m+=` + xCOffset = xC + `+b+`; + + if(xR >= 0 && xR < `+o+` && + xCOffset >= 0 && xCOffset < `+a+`) { + xTexelR`+v+"C"+(g+2)+` = getX(batch, xR, xCOffset, d1); + } + + xR`+v+"C"+(g+1)+" = xTexelR"+v+"C"+(g+2)+`; + `}}else g= 0 && xR < `+o+`) { + `,s%2==1?(m+=` + xCOffset = xC + 1 - `+c+`; + if(xCOffset >= 0 && xCOffset < `+a+`) { + xTexelR`+v+"C"+g+` = getX(batch, xR, xCOffset, d1); + } else { + xTexelR`+v+"C"+g+` = vec4(0.); + } + + if(xC + 1 >= 0 && xC + 1 < `+a+`) { + xTexelR`+v+"C"+(g+2)+` = getX(batch, xR, xC + 1, d1); + } else { + xTexelR`+v+"C"+(g+2)+` = vec4(0.); + } + + xR`+v+"C"+g+` = vec4( + xTexelR`+v+"C"+g+".zw, xTexelR"+v+"C"+(g+2)+`.zw); + `,g+1= 0 && xCOffset < `+a+`) { + final = getX(batch, xR, xCOffset, d1); + } + xR`+v+"C"+(g+1)+" = vec4(xTexelR"+v+"C"+(g+2)+`.xy, final.xy); + `)):(m+=` + if(xC >= 0 && xC < `+a+`) { + xTexelR`+v+"C"+g+` = getX(batch, xR, xC, d1); + } else { + xTexelR`+v+"C"+g+` = vec4(0.); + } + + xCOffset = xC + `+c+`; + if(xCOffset >= 0 && xCOffset < `+a+`) { + xTexelR`+v+"C"+(g+2)+` = getX(batch, xR, xCOffset, d1); + } else { + xTexelR`+v+"C"+(g+2)+` = vec4(0.); + } + + xR`+v+"C"+g+` = vec4( + xTexelR`+v+"C"+g+".xy, xTexelR"+v+"C"+(g+2)+`.xy); + `,g+11?[""+(i-1)/(l-1),"(y2-y1) * height_ratio","y1*"+p+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+p],g=v[0],x=v[1],b=v[2],y=h>1?[""+(s-1)/(h-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],w=y[0],_=y[1],S=y[2];this.userCode=` + const float height_ratio = float(`+g+`); + const float width_ratio = float(`+w+`); + 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 >= `+a+`) { + return; + } + + float height_scale = `+x+`; + float width_scale = `+_+`; + + float in_y = `+b+`; + if( in_y < 0.0 || in_y > `+p+` ) { + setOutput(float(`+o+`)); + return; + } + float in_x = `+S+`; + if( in_x < 0.0 || in_x > `+m+` ) { + setOutput(float(`+o+`)); + return; + } + + vec2 sourceFracIndexCR = vec2(in_x,in_y); + if(`+f+` == 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); + } + } + `},Mv=function(r,t,e){this.variableNames=["x"],this.outputShape=r;var n=r.length,o=r[r.length-1],a=e?"<":">";this.userCode=` + int getIndex(int i) { + `+(e?"return "+o+" -i - 1;":"return i;")+` + } + + void main() { + `+_e(n)+` coords = getOutputCoords(); + int end = `+lu(n,"coords")+`; + float val = 0.0; + for (int i = `+o+` - 1; i >= 0; i -= 1) { + int idx = getIndex(i); + if (idx `+a+` end) { + continue; + } + if (idx == end && `+t+`) { + continue; + } + `+lu(n,"coords")+` = idx; + val += getX(`+(function(i,s){if(i===1)return""+s;if(i===2)return s+".x, "+s+".y";if(i===3)return s+".x, "+s+".y, "+s+".z";if(i===4)return s+".x, "+s+".y, "+s+".z, "+s+".w";throw Error("Cumulative sum for rank "+i+" is not yet supported")})(n,"coords")+`); + } + setOutput(val); + } + `};function lu(r,t){if(r===1)return""+t;if(r===2)return t+".y";if(r===3)return t+".z";if(r===4)return t+".w";throw Error("Cumulative sum for rank "+r+" is not yet supported")}var Ov=function(r){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=_r.DENSE;var t=gr(r),e=Je();this.outputShape=r,this.userCode=` + ivec3 outCoordsFromFlatIndex(int index) { + `+En(["r","c","d"],r)+` + return ivec3(r, c, d); + } + + void main() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(`+t[0]+", "+t[1]+`)); + int index = 4 * (resTexRC.x * `+t[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); + } + + `+e.output+` = result; + } + `},Bv=function(r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=_r.DENSE;var t=gr(r),e=Je();this.outputShape=r,this.userCode=` + ivec3 outCoordsFromFlatIndex(int index) { + `+En(["r","c","d"],r)+` + return ivec3(r, c, d); + } + + void main() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(`+t[0]+", "+t[1]+`)); + int index = 4 * (resTexRC.x * `+t[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)); + } + + `+e.output+` = result; + } + `},Lv=(function(){function r(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,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 / `+e+`; + int offset_h = imod(h, `+e+`); + int in_w = w / `+e+`; + int offset_w = imod(w, `+e+`); + int offset_d = (offset_h * `+e+` + offset_w) * + `+this.getOutputDepthSize()+`; + int in_d = d + offset_d; + + float result = `+this.getInputSamplingString()+`; + setOutput(result); + } + `}return r.prototype.getHeightCoordString=function(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"},r.prototype.getWidthCoordString=function(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"},r.prototype.getDepthCoordString=function(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"},r.prototype.getOutputDepthSize=function(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]},r.prototype.getInputSamplingString=function(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},r})(),Wv=function(r){this.variableNames=["X"],this.outputShape=[r,r],this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0; + setOutput(val); + } + `},zv=function(r){this.variableNames=["A"],this.outTexUsage=ct.DOWNLOAD;var t=Je();this.outputShape=r,this.userCode=` + `+xl+` + + void main() { + float x = getAAtOutCoords(); + `+t.output+` = encode_float(x); + } + `},Uv=function(r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=ct.DOWNLOAD;var t=Je();this.outputShape=r,this.userCode=` + `+xl+` + + void main() { + ivec3 coords = getOutputCoords(); + float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z)); + `+t.output+` = encode_float(x); + } + `},Vv=function(r,t,e){e===void 0&&(e=!1),this.variableNames=["A"];var n=Je(),o=t[0],a=t[1];this.outputShape=r;var i="result";e&&(i="floor(result * 255. + 0.5)"),this.userCode=` + `+Li(r)+` + + void main() { + ivec3 coords = getOutputCoords(); + + int flatIndex = getFlatIndex(coords); + int offset = imod(flatIndex, 4); + + flatIndex = idiv(flatIndex, 4, 1.); + + int r = flatIndex / `+a+`; + int c = imod(flatIndex, `+a+`); + vec2 uv = (vec2(c, r) + halfCR) / vec2(`+a+".0, "+o+`.0); + vec4 values = `+n.texture2D+`(A, uv); + + float result; + + if(offset == 0) { + result = values[0]; + } else if(offset == 1) { + result = values[1]; + } else if(offset == 2) { + result = values[2]; + } else { + result = values[3]; + } + + `+n.output+" = vec4("+i+`, 0., 0., 0.); + } + `},Gv=function(r,t,e){e===void 0&&(e=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var n=Je(),o=t[0],a=t[1];this.outputShape=r;var i="",s="result";e&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var c=0;c<=1;c++){var l=2*u+c;i+=` + localCoords = coords; + if(localCoords[2] + `+c+" < "+r[2]+`) { + localCoords[2] += `+c+`; + if(localCoords[1] + `+u+" < "+r[1]+`) { + localCoords[1] += `+u+`; + + flatIndex = getFlatIndex(localCoords); + offset = imod(flatIndex, 4); + + flatIndex = idiv(flatIndex, 4, 1.); + + r = flatIndex / `+a+`; + c = imod(flatIndex, `+a+`); + uv = (vec2(c, r) + halfCR) / vec2(`+a+".0, "+o+`.0); + values = `+n.texture2D+`(A, uv); + + if(offset == 0) { + result[`+l+`] = values[0]; + } else if(offset == 1) { + result[`+l+`] = values[1]; + } else if(offset == 2) { + result[`+l+`] = values[2]; + } else { + result[`+l+`] = values[3]; + } + } + } + `}this.userCode=` + `+Li(r)+` + + void main() { + ivec3 coords = getOutputCoords(); + + vec4 result = vec4(0.); + int flatIndex, r, c, offset; + ivec3 localCoords; + vec2 uv; + vec4 values; + + `+i+` + + `+n.output+" = "+s+`; + } + `},Hv="return real * expR - imag * expI;",qv="return real * expI + imag * expR;",hu=function(r,t,e){this.variableNames=["real","imag"];var n=t[1];this.outputShape=t;var o=e?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,a=e?n+".0":"1.0";this.userCode=` + const float exponentMultiplier = `+o+`; + + float unaryOpComplex(float real, float expR, float imag, float expI) { + `+r+` + } + + float mulMatDFT(int batch, int index) { + float indexRatio = float(index) / float(`+n+`); + float exponentMultiplierTimesIndexRatio = + exponentMultiplier * indexRatio; + + float result = 0.0; + + for (int i = 0; i < `+n+`; 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) / `+a+`; + } + + return result; + } + + void main() { + ivec2 coords = getOutputCoords(); + setOutput(mulMatDFT(coords[0], coords[1])); + } + `},jv=(function(){function r(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode=` + uniform float value; + void main() { + // Input can be obtained from uniform value. + setOutput(value); + } + `}return r.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,o){e.valueLoc==null&&(e.valueLoc=n.getUniformLocationNoThrow(o,"value")),n.gl.uniform1f(e.valueLoc,t)}},r})(),Kv=function(r,t,e){this.variableNames=["A","indices"];var n=r.slice();n[e]=t,this.outputShape=n,this.rank=n.length;var o=_e(this.rank),a=(function(i,s){var u=i.length;if(u>4)throw Error("Gather for rank "+u+" is not yet supported");if(u===1)return"int(getIndices(resRC))";for(var c=["resRC.x","resRC.y","resRC.z","resRC.w"],l=[],h=0;h1?"strides[j]":"strides";this.userCode=` + `+n+" strides = "+n+"("+this.strides+`); + void main() { + `+o+` coords = getOutputCoords(); + int flattenIndex = 0; + for (int j = 0; j < `+this.sliceDim+`; j++) { + int index = round(getIndices(coords[0], j)); + flattenIndex += index * `+a+`; + } + setOutput(getX(flattenIndex, coords[1])); + } + `};function _l(r,t){var e=Je();return lc(r,t,e.version+` + precision highp float; + `+e.attribute+` vec3 clipSpacePos; + `+e.attribute+` vec2 uv; + `+e.varyingVs+` vec2 resultUV; + + void main() { + gl_Position = vec4(clipSpacePos, 1); + resultUV = uv; + }`)}function El(r,t){return pc(r,t,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function Il(r,t){return vc(r,t,new Uint16Array([0,1,2,2,1,3]))}function zr(r,t,e,n,o,a,i){gc(e,n);var s=mc(r,t),u=r.TEXTURE_2D;return X(r,t,(function(){return r.bindTexture(u,s)})),X(r,t,(function(){return r.texParameteri(u,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE)})),X(r,t,(function(){return r.texParameteri(u,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)})),X(r,t,(function(){return r.texParameteri(u,r.TEXTURE_MIN_FILTER,r.NEAREST)})),X(r,t,(function(){return r.texParameteri(u,r.TEXTURE_MAG_FILTER,r.NEAREST)})),X(r,t,(function(){return r.texImage2D(u,0,o,e,n,0,a,i,null)})),X(r,t,(function(){return r.bindTexture(r.TEXTURE_2D,null)})),s}function Rl(r,t,e,n,o){var a=To(e,n);return zr(r,t,a[0],a[1],o.internalFormatFloat,o.textureFormatFloat,r.FLOAT)}function kl(r,t,e,n,o){var a=To(e,n);return zr(r,t,a[0],a[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat)}function Sl(r,t,e,n,o){var a=To(e,n);return zr(r,t,a[0],a[1],r.RGBA,r.RGBA,r.UNSIGNED_BYTE)}function Al(r,t,e,n,o){var a=Lr(e,n);return zr(r,t,a[0],a[1],o.internalFormatPackedFloat,r.RGBA,r.FLOAT)}function Dl(r,t,e,n,o){var a=Lr(e,n);return zr(r,t,a[0],a[1],o.internalFormatPackedHalfFloat,r.RGBA,o.textureTypeHalfFloat)}function Tl(r,t,e,n){return X(r,t,(function(){return r.bindBuffer(r.ARRAY_BUFFER,n)})),Ga(r,t,e,"clipSpacePos",n,3,20,0)&&Ga(r,t,e,"uv",n,2,20,12)}function Fl(r,t,e,n,o,a,i){var s,u,c;X(r,t,(function(){return r.bindTexture(r.TEXTURE_2D,e)})),a instanceof Uint8Array?(s=new Uint8Array(n*o*4),u=r.UNSIGNED_BYTE,c=r.RGBA):(s=new Float32Array(n*o*4),u=r.FLOAT,c=i.internalFormatPackedFloat),s.set(a),X(r,t,(function(){return r.texImage2D(r.TEXTURE_2D,0,c,n,o,0,r.RGBA,u,s)})),X(r,t,(function(){return r.bindTexture(r.TEXTURE_2D,null)}))}function Nl(r,t,e,n){X(r,t,(function(){return r.bindTexture(r.TEXTURE_2D,e)})),n.data instanceof Uint8Array?X(r,t,(function(){return r.texImage2D(r.TEXTURE_2D,0,r.RGBA,n.width,n.height,0,r.RGBA,r.UNSIGNED_BYTE,n.data)})):X(r,t,(function(){return r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,n)})),X(r,t,(function(){return r.bindTexture(r.TEXTURE_2D,null)}))}function Pl(r,t,e,n,o){var a=r.createBuffer();X(r,t,(function(){return r.bindBuffer(r.PIXEL_PACK_BUFFER,a)}));var i=16*e*n;return X(r,t,(function(){return r.bufferData(r.PIXEL_PACK_BUFFER,i,r.STREAM_READ)})),X(r,t,(function(){return r.readPixels(0,0,n,e,r.RGBA,r.FLOAT,0)})),X(r,t,(function(){return r.bindBuffer(r.PIXEL_PACK_BUFFER,null)})),a}function Ml(r,t,e){var n=r,o=new Float32Array(e);return n.bindBuffer(n.PIXEL_PACK_BUFFER,t),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,o),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),o}function Ol(r,t,e,n,o){var a=To(e,n),i=a[0],s=a[1],u=new Uint8Array(e*n*4);return X(r,t,(function(){return r.readPixels(0,0,i,s,o.downloadTextureFormat,r.UNSIGNED_BYTE,u)})),new Float32Array(u.buffer)}function Bl(r,t,e,n,o,a,i,s){var u=r,c=new Float32Array((function(l,h){var f=Lr(l,h);return f[0]*f[1]*4})(a,i));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,c),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),c}function Ll(r,t,e,n){var o=new Float32Array(e*n*4);return X(r,t,(function(){return r.readPixels(0,0,n,e,r.RGBA,r.FLOAT,o)})),o}var Yv=Object.freeze({createVertexShader:_l,createVertexBuffer:El,createIndexBuffer:Il,createFloat32MatrixTexture:Rl,createFloat16MatrixTexture:kl,createUnsignedBytesMatrixTexture:Sl,createPackedMatrixTexture:Al,createFloat16PackedMatrixTexture:Dl,bindVertexProgramAttributeStreams:Tl,uploadDenseMatrixToTexture:Fl,uploadPixelDataToTexture:Nl,createBufferFromOutputTexture:Pl,downloadFloat32MatrixFromBuffer:Ml,downloadByteEncodedFloatMatrixFromOutputTexture:Ol,downloadPackedMatrixFromBuffer:Bl,downloadMatrixFromPackedOutputTexture:Ll}),Wl=(function(){function r(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=M().getNumber("WEBGL_VERSION");t!=null?(this.gl=t,sc(e,t)):this.gl=Bt(e);var n="WEBGL_color_buffer_float";if(M().getNumber("WEBGL_VERSION")===1){if(this.textureFloatExtension=pr(this.gl,this.debug,"OES_texture_float"),lt(this.gl,"OES_texture_half_float"))this.textureHalfFloatExtension=pr(this.gl,this.debug,"OES_texture_half_float");else if(M().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(n),lt(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=pr(this.gl,this.debug,"EXT_color_buffer_half_float");else if(M().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(n="EXT_color_buffer_float",lt(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!lt(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}this.vertexBuffer=El(this.gl,this.debug),this.indexBuffer=Il(this.gl,this.debug),this.framebuffer=yc(this.gl,this.debug),this.textureConfig=mi(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(r.prototype,"debug",{get:function(){return M().getBool("DEBUG")},enumerable:!0,configurable:!0}),r.prototype.dispose=function(){var t=this;if(!this.disposed){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.");var e=this.gl;X(e,this.debug,(function(){return e.finish()})),X(e,this.debug,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)})),X(e,this.debug,(function(){return e.deleteFramebuffer(t.framebuffer)})),X(e,this.debug,(function(){return e.bindBuffer(e.ARRAY_BUFFER,null)})),X(e,this.debug,(function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)})),X(e,this.debug,(function(){return e.deleteBuffer(t.indexBuffer)})),this.disposed=!0}},r.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),Rl(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),kl(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),Sl(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),Nl(this.gl,this.debug,t,e)},r.prototype.uploadDenseMatrixToTexture=function(t,e,n,o){this.throwIfDisposed(),Fl(this.gl,this.debug,t,e,n,o,this.textureConfig)},r.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Dl(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Al(this.gl,this.debug,t,e,this.textureConfig)},r.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(Ha(this.gl,this.debug,this.framebuffer),this.outputTexture=null),X(this.gl,this.debug,(function(){return e.gl.deleteTexture(t)}))},r.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var o=this;return this.downloadMatrixDriver(t,(function(){return Ol(o.gl,o.debug,e,n,o.textureConfig)}))},r.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,o,a,i){return Bl(this.gl,t,0,0,0,a,i,this.textureConfig)},r.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return Ml(this.gl,t,e)},r.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var o=Pl(this.gl,this.debug,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),o},r.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},r.prototype.createFence=function(t){var e,n,o=this;if(M().getBool("WEBGL_FENCE_API_ENABLED")){var a=t,i=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var s=a.clientWaitSync(i,0,0);return s===a.ALREADY_SIGNALED||s===a.CONDITION_SATISFIED},e=i}else M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return o.isQueryAvailable(e,M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:e,isFencePassed:n}},r.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var o=this;return this.downloadMatrixDriver(t,(function(){return Ll(o.gl,o.debug,e,n)}))},r.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=hc(e,this.debug,t),o=_l(e,this.debug),a=fc(e,this.debug);return X(e,this.debug,(function(){return e.attachShader(a,o)})),X(e,this.debug,(function(){return e.attachShader(a,n)})),dc(e,this.debug,a),this.debug&&lo(e,this.debug,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=Tl(e,this.debug,this.program,this.vertexBuffer)),a},r.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),t!=null&&X(this.gl,this.debug,(function(){return e.gl.deleteProgram(t)}))},r.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,this.program!=null&&this.debug&&lo(this.gl,this.debug,this.program),X(this.gl,this.debug,(function(){return e.gl.useProgram(t)}))},r.prototype.getUniformLocation=function(t,e,n){return n===void 0&&(n=!0),this.throwIfDisposed(),n?bc(this.gl,this.debug,t,e):wc(this.gl,t,e)},r.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),X(this.gl,this.debug,(function(){return n.gl.getAttribLocation(t,e)}))},r.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},r.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),Cc(this.gl,this.debug,this.program,t,e,n)},r.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},r.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var o=Lr(e,n),a=o[0],i=o[1];this.setOutputMatrixTextureDriver(t,a,i)},r.prototype.setOutputMatrixWriteRegion=function(t,e,n,o){this.setOutputMatrixWriteRegionDriver(n,t,o,e)},r.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,o){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},r.prototype.debugValidate=function(){this.program!=null&&lo(this.gl,this.debug,this.program),vr(this.gl)},r.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),X(t,this.debug,(function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)}))},r.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),X(this.gl,this.debug,(function(){return t.gl.finish()}))},r.prototype.getQueryTimerExtension=function(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=pr(this.gl,this.debug,M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},r.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},r.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},r.prototype.beginQuery=function(){if(M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}var o=this.getQueryTimerExtensionWebGL1(),a=o.createQueryEXT();return o.beginQueryEXT(o.TIME_ELAPSED_EXT,a),a},r.prototype.endQuery=function(){if(M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")!==2){var t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}else{var e=this.gl,n=this.getQueryTimerExtensionWebGL2();e.endQuery(n.TIME_ELAPSED_EXT)}},r.prototype.waitForQueryAndGetTime=function(t){return J(this,void 0,void 0,(function(){var e=this;return Q(this,(function(n){switch(n.label){case 0:return[4,Ma((function(){return e.disposed||e.isQueryAvailable(t,M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}))];case 1:return n.sent(),[2,this.getQueryTime(t,M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}}))}))},r.prototype.getQueryTime=function(t,e){if(e===0)return null;if(e===2){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var o=this.getQueryTimerExtensionWebGL1();return o.getQueryObjectEXT(t,o.QUERY_RESULT_EXT)/1e6},r.prototype.isQueryAvailable=function(t,e){if(e===0)return!0;if(e===2){var n=this.gl,o=this.getQueryTimerExtensionWebGL2(),a=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(o.GPU_DISJOINT_EXT)),a&&!this.disjoint}return a=(o=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,o.QUERY_RESULT_AVAILABLE_EXT),this.disjoint==null&&(this.disjoint=this.gl.getParameter(o.GPU_DISJOINT_EXT)),a&&!this.disjoint},r.prototype.pollFence=function(t){var e=this;return new Promise((function(n){e.addItemToPoll((function(){return t.isFencePassed()}),(function(){return n()}))}))},r.prototype.pollItems=function(){for(var t=(function(n){for(var o=0;o1||Ma((function(){return n.pollItems(),n.itemsToPoll.length===0}))},r.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),ho(this.gl,this.debug,t,this.framebuffer),this.debug&&vr(this.gl)},r.prototype.unbindTextureToFrameBuffer=function(){this.outputTexture!=null?(ho(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&vr(this.gl)):Ha(this.gl,this.debug,this.framebuffer)},r.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},r.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var o=this.gl;ho(o,this.debug,t,this.framebuffer),this.debug&&vr(o),this.outputTexture=t,X(o,this.debug,(function(){return o.viewport(0,0,e,n)})),X(o,this.debug,(function(){return o.scissor(0,0,e,n)}))},r.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,o){var a=this;this.throwIfDisposed(),X(this.gl,this.debug,(function(){return a.gl.scissor(t,e,n,o)}))},r.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},r.prototype.throwIfNoProgram=function(){if(this.program==null)throw new Error("No GPU program is currently set.")},r})();function fu(r,t){if(r.length!==t.length)throw Error("Binary was compiled with "+r.length+" inputs, but was executed with "+t.length+" inputs");r.forEach((function(e,n){var o=e.logicalShape,a=t[n],i=a.shape;if(!Ne(o,i))throw Error("Binary was compiled with different shapes than the current args. Shapes "+o+" and "+i+" must match");if(!e.isUniform||!a.isUniform){var s=e.texShape,u=a.isUniform?null:a.texData.texShape;if(!Ne(s,u))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+s+" and "+u+" must match")}}))}var $v=function(r,t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r;for(var n=e.filterWidth,o=e.inChannels,a=e.strideWidth,i=e.strideHeight,s=e.padInfo,u=e.outWidth,c=e.dilationWidth,l=e.dilationHeight,h=e.dataFormat,f=s.left,d=s.top,p=o*n,m=Je(),v=h==="channelsLast",g=v?0:1,x=v?1:2,b="",y=0;y<=1;y++)for(var w=0;w<=1;w++)b+=` + blockIndex = rc.y + `+w+`; + pos = rc.x + `+y+`; + + if(blockIndex < `+r[1]+" && pos < "+r[0]+`) { + offsetY = int(blockIndex / (`+u+")) * "+i+" - "+d+`; + d0 = offsetY + `+l+" * (pos / "+p+`); + + if(d0 < `+t[g]+` && d0 >= 0) { + + offsetX = int(mod(float(blockIndex), `+u+".) * "+a+". - "+f+`.); + d1 = offsetX + `+c+" * (int(mod(float(pos), "+p+".) / "+o+`.)); + + if(d1 < `+t[x]+` && d1 >= 0) { + + ch = int(mod(float(pos), `+o+`.)); + + if (`+v+`) { + innerDims = vec2(d1, ch); + result[`+(2*y+w)+`] = getChannel( + getA(d0, int(innerDims.x), + int(innerDims.y)), innerDims); + } else { + innerDims = vec2(d0, d1); + result[`+(2*y+w)+`] = getChannel( + getA(ch, int(innerDims.x), + int(innerDims.y)), innerDims); + } + } + } + } + `;this.userCode=` + void main() { + ivec2 rc = getOutputCoords(); + + vec4 result = vec4(0); + + int blockIndex, pos, offsetY, d0, offsetX, d1, ch; + vec2 innerDims; + + `+b+` + + `+m.output+` = result; + } + `},Jv=function(r,t,e,n,o){this.variableNames=["x"],this.outputShape=[];var a,i=t,s=r[3]-1;this.outputShape=r;var u="float("+e+") + float("+n+") * sum";a=o===.5?"inversesqrt("+u+")":o===1?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",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 = -`+i+"; j <= "+i+`; j++) { + int idx = d + j; + if (idx >= 0 && idx <= `+s+`) { + float z = getX(b, r, c, idx); + sum += z * z; + } + } + float val = x * `+a+`; + setOutput(val); + } + `},Qv=function(r,t,e,n,o){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=r,this.depth=r[3],this.depthRadius=t,this.bias=e,this.alpha=n,this.beta=o,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(`+n+") * norm + float("+e+`); + + 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(`+n+`) + * float(`+o+`) + * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d) + / norm; + if (k == d) { + dyi += pow(norm, -1.0 * `+o+`); + } + if (k == coords[3]) { + dyi *= getDy(b, r, c, d); + result += dyi; + } + } + else { + break; + } + } + } + setOutput(result); + } + `},Zv=function(r,t,e,n,o){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var a,i=t,s=r[3]-1;this.outputShape=r;var u="float("+e+") + float("+n+") * sum";a=o===.5?"inversesqrt("+u+")":o===1?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",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 - `+i+`; + 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 = - `+i+"; j <= "+i+`; j++) { + ivec2 idx = depth + j; + bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0)); + bvec2 belowUpperBound = lessThanEqual(idx, ivec2(`+s+`)); + + 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 * `+a+`; + setOutput(result); + } + `},em=function(r){this.variableNames=["dy","maxPos"],this.outputShape=r.inShape;var t=r.strideHeight,e=r.strideWidth,n=r.dilationHeight,o=r.effectiveFilterHeight,a=r.effectiveFilterWidth,i=o-1-r.padInfo.top,s=a-1-r.padInfo.left,u=o*a-1;this.userCode=` + const ivec2 pads = ivec2(`+i+", "+s+`); + + 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 < `+o+`; + wR += `+n+`) { + float dyR = float(dyRCorner + wR) / `+t+`.0; + + if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < `+a+`; wC++) { + float dyC = float(dyCCorner + wC) / `+e+`.0; + + if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(b, idyR, idyC, d); + int maxPosValue = `+u+` - int(getMaxPos(b, idyR, idyC, d)); + + // Get the current value, check it against the value from the + // position matrix. + int curPosValue = wR * `+a+` + wC; + float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); + + dotProd += dyValue * mask; + } + } + setOutput(dotProd); + } + `},tm=function(r){this.variableNames=["dy","maxPos"],this.outputShape=r.inShape;var t=r.strideDepth,e=r.strideHeight,n=r.strideWidth,o=r.dilationDepth,a=r.dilationHeight,i=r.dilationWidth,s=r.effectiveFilterDepth,u=r.effectiveFilterHeight,c=r.effectiveFilterWidth,l=s-1-r.padInfo.front,h=u-1-r.padInfo.top,f=c-1-r.padInfo.left,d=s*u*c-1;this.userCode=` + const ivec3 pads = ivec3(`+l+", "+h+", "+f+`); + + 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 < `+s+`; + wD += `+o+`) { + float dyD = float(dyDCorner + wD) / `+t+`.0; + + if (dyD < 0.0 || dyD >= `+r.outDepth+`.0 || fract(dyD) > 0.0) { + continue; + } + int idyD = int(dyD); + + for (int wR = 0; wR < `+u+`; + wR += `+a+`) { + float dyR = float(dyRCorner + wR) / `+e+`.0; + + if (dyR < 0.0 || dyR >= `+r.outHeight+`.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < `+c+`; + wC += `+i+`) { + float dyC = float(dyCCorner + wC) / `+n+`.0; + + if (dyC < 0.0 || dyC >= `+r.outWidth+`.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(batch, idyD, idyR, idyC, ch); + int maxPosValue = `+d+` - + int(getMaxPos(batch, idyD, idyR, idyC, ch)); + + // Get the current value, check it against the value from the + // position matrix. + int curPosValue = + wD * `+u+" * "+c+` + + wR * `+c+` + wC; + float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); + + dotProd += dyValue * mask; + } + } + } + setOutput(dotProd); + } + `},ma=function(r,t,e,n,o,a,i){e===void 0&&(e=!1),n===void 0&&(n=!1),o===void 0&&(o=!1),a===void 0&&(a=null),i===void 0&&(i=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;var s=e?r[1]:r[2],u=Math.ceil(s/2),c=e?"i * 2, rc.y":"rc.y, i * 2",l=n?"rc.z, i * 2":"i * 2, rc.z",h=e?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=n?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],d="",p="";a&&(d=i?`vec4 activation(vec4 a) { + vec4 b = getPreluActivationWeightsAtOutCoords(); + `+a+` + }`:`vec4 activation(vec4 x) { + `+a+` + }`,p="result = activation(result);");var m=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode=` + `+d+` + + const float sharedDimension = `+u+`.0; + + vec4 dot2x2ARowBCol(ivec3 rc) { + vec4 result = vec4(0); + for (int i = 0; i < `+u+`; i++) { + vec4 a = getMatrixA(rc.x, `+c+`); + vec4 b = getMatrixB(rc.x, `+l+`); + + // These swizzled products need to be separately added. + // See: https://github.com/tensorflow/tfjs/issues/1735 + result += (`+h[0]+" * "+f[0]+`); + result += (`+h[1]+" * "+f[1]+`); + } + return result; + } + + void main() { + ivec3 rc = getOutputCoords(); + vec4 result = dot2x2ARowBCol(rc); + + `+m+` + + `+p+` + + setOutput(result); + } + `},nm=(function(){function r(t,e,n){this.variableNames=["probs"],this.outputShape=[t,n],this.userCode=` + uniform float seed; + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + + float r = random(seed); + float cdf = 0.0; + + for (int i = 0; i < `+(e-1)+`; i++) { + cdf += getProbs(batch, i); + + if (r < cdf) { + setOutput(float(i)); + return; + } + } + + // If no other event happened, last event happened. + setOutput(float(`+(e-1)+`)); + } + `}return r.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,o){e.seedLoc==null&&(e.seedLoc=n.getUniformLocation(o,"seed")),n.gl.uniform1f(e.seedLoc,t)}},r})(),rm=function(r,t,e,n){this.variableNames=["indices"],this.outputShape=[r,t],this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int index = round(getIndices(coords.x)); + setOutput(mix(float(`+n+"), float("+e+`), + float(index == coords.y))); + } + `},om=function(r){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=r;var t=r.length;if(t===0)this.userCode=` + void main() { + setOutput(vec4(getA(), 0., 0., 0.)); + } + `;else{var e=rt("rc",t),n=_e(t),o=(function(s,u,c){if(s===1)return"rc > "+u[0];for(var l="",h=s-2;h= "+u[h],h= `+u+`; + bool rEdge = rp1 >= `+c+`; + `})(t,r[r.length-1],r[r.length-2],e),i=(function(s,u){var c=s.length,l=(function(h,f){for(var d=[],p=0;p<=1;p++)for(var m=0;m<=1;m++){for(var v=(p===0?"r":"rp1")+", "+(m===0?"c":"cp1"),g=2;g= `+s[0]+` ? 0. : getA(rc + 1), + 0, 0`:"getA("+l[0]+`), + cEdge ? 0. : getA(`+l[1]+`), + rEdge ? 0. : getA(`+l[2]+`), + rEdge || cEdge ? 0. : getA(`+l[3]+")"})(r,e);this.userCode=` + void main() { + `+n+` rc = getOutputCoords(); + + if(`+o+`) { + setOutput(vec4(0)); + } else { + `+a+` + + setOutput(vec4(`+i+`)); + } + } + `}},am=function(r,t,e){this.variableNames=["x"],this.outputShape=t.map((function(u,c){return u[0]+r[c]+u[1]}));var n=r.length,o=_e(n),a=t.map((function(u){return u[0]})).join(","),i=t.map((function(u,c){return u[0]+r[c]})).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);this.userCode=n!==1?` + `+o+" start = "+o+"("+a+`); + `+o+" end = "+o+"("+i+`); + + void main() { + `+o+` outC = getOutputCoords(); + if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) { + setOutput(float(`+e+`)); + } else { + `+o+` coords = outC - start; + setOutput(getX(`+s+`)); + } + } + `:` + int start = `+a+`; + int end = `+i+`; + + void main() { + int outC = getOutputCoords(); + if (outC < start || outC >= end) { + setOutput(float(`+e+`)); + } else { + setOutput(getX(outC - start)); + } + } + `},im=function(r,t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((function(v,g){return v[0]+r[g]+v[1]}));for(var n=r.length,o=_e(n),a=t.map((function(v){return v[0]})).join(","),i=t.map((function(v,g){return v[0]+r[g]})).join(","),s=rt("rc",n),u=rt("source",n),c=s[n-1]+" < "+this.outputShape[n-1],l=n===1?"source":"vec2("+u.slice(-2).join()+")",h=[o+" rc = outputLoc;",s[n-1]+` += 1; + if(`+c+`) { + `,n===1?"":`} + rc = outputLoc; + `+s[n-2]+` += 1; + if(`+s[n-2]+" < "+this.outputShape[n-2]+") {",n===1?"":" "+s[n-1]+` += 1; + if(`+c+") {"],f=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",d="",p=0,m=n===1?2:4;p= `+r.inHeight+`) { + continue; + } + + for (int wC = 0; wC < `+c+`; + wC += `+s+`) { + int xC = xCCorner + wC; + + if (xC < 0 || xC >= `+r.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 >= currMinMaxValue) { + minMaxValue = value; + minMaxValueFound = 1.0; + minMaxPosition = wR * `+c+` + wC; + } + } + } + setOutput(float(minMaxPosition)); + } + `;else{var p=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";t==="avg"&&(p="avgValue / count");var m=4*Math.floor(n/4),v=n%4,g=` + if (`+f+`) { + avgValue += dot(values, ones); + } else { + minMaxValue = max(values, minMaxValue); + } + `;this.userCode=` + const ivec2 strides = ivec2(`+o+", "+a+`); + const ivec2 pads = ivec2(`+l+", "+h+`); + const float initializationValue = `+d+`; + 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 >= `+r.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(`+d+`); + float avgValue = 0.0; + count = 0.0; + + for (int wR = 0; wR < `+u+`; + wR += `+i+`) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= `+r.inHeight+`) { + continue; + } + + for (int wC = 0; wC < `+m+`; wC += 4) { + int xC = xCCorner + wC * `+s+`; + + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + `+s+`, d), + getValue(batch, xR, xC + 2 * `+s+`, d), + getValue(batch, xR, xC + 3 * `+s+`, d) + ); + + `+g+` + } + + int xC = xCCorner + `+m+`; + if (`+(v===1)+`) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + initializationValue, + initializationValue, + initializationValue + ); + + `+g+` + } else if (`+(v===2)+`) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + `+s+`, d), + initializationValue, + initializationValue + ); + + `+g+` + } else if (`+(v===3)+`) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + `+s+`, d), + getValue(batch, xR, xC + 2 * `+s+`, d), + initializationValue + ); + + `+g+` + } + } + setOutput(`+p+`); + } + `}},ya=function(r,t,e){if(this.variableNames=["x"],t==="avg"&&e)throw new Error("Cannot compute positions for average pool.");var n=r.filterWidth,o=r.strideDepth,a=r.strideHeight,i=r.strideWidth,s=r.dilationDepth,u=r.dilationHeight,c=r.dilationWidth,l=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,d=r.padInfo.front,p=r.padInfo.top,m=r.padInfo.left;this.outputShape=r.outShape;var v=t==="avg",g="0.0";if(v||(g="-1.0 / 1e-20"),e)this.userCode=` + const ivec3 strides = + ivec3(`+o+", "+a+", "+i+`); + const ivec3 pads = ivec3(`+d+", "+p+", "+m+`); + + 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 < `+l+`; + wD += `+s+`) { + int xD = xDCorner + wD; + + if (xD < 0 || xD >= `+r.inDepth+`) { + continue; + } + + for (int wR = 0; wR < `+h+`; + wR += `+u+`) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= `+r.inHeight+`) { + continue; + } + + for (int wC = 0; wC < `+f+`; + wC += `+c+`) { + int xC = xCCorner + wC; + + if (xC < 0 || xC >= `+r.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 = + wD * `+h+" * "+f+` + + wR * `+f+` + wC;; + } + } + } + } + setOutput(float(minMaxPosition)); + } + `;else{var x=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";t==="avg"&&(x="avgValue / count");var b=4*Math.floor(n/4),y=n%4,w=` + if (`+v+`) { + avgValue += dot(values, ones); + } else { + minMaxValue = max(values, minMaxValue); + } + `;this.userCode=` + const ivec3 strides = + ivec3(`+o+", "+a+", "+i+`); + const ivec3 pads = ivec3(`+d+", "+p+", "+m+`); + const float initializationValue = `+g+`; + 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 >= `+r.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(`+g+`); + float avgValue = 0.0; + count = 0.0; + + for (int wD = 0; wD < `+l+`; + wD += `+s+`) { + int xD = xDCorner + wD; + + if (xD < 0 || xD >= `+r.inDepth+`) { + continue; + } + + for (int wR = 0; wR < `+h+`; + wR += `+u+`) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= `+r.inHeight+`) { + continue; + } + + for (int wC = 0; wC < `+b+`; wC += 4) { + int xC = xCCorner + wC * `+c+`; + + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + `+c+`, ch), + getValue(batch, xD, xR, xC + 2 * `+c+`, ch), + getValue(batch, xD, xR, xC + 3 * `+c+`, ch) + ); + + `+w+` + } + + int xC = xCCorner + `+b+`; + if (`+(y===1)+`) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + initializationValue, + initializationValue, + initializationValue + ); + + `+w+` + } else if (`+(y===2)+`) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + `+c+`, ch), + initializationValue, + initializationValue + ); + + `+w+` + } else if (`+(y===3)+`) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + `+c+`, ch), + getValue(batch, xD, xR, xC + 2 * `+c+`, ch), + initializationValue + ); + + `+w+` + } + } + setOutput(`+x+`); + } + } + `}},sm=function(r,t){this.variableNames=["x"];var e=r.windowSize,n=r.batchSize,o=r.inSize,a=Math.ceil(o/e);this.outputShape=[n,a];var i="0.0",s="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",s="min"):t==="max"&&(i="-1.0 / 1e-20",s="max");var u=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";t==="sum"?u="sumValue":t==="prod"?u="prodValue":t==="all"?u="allValue":t==="any"&&(u="anyValue");var c=4*Math.floor(e/4),l=e%4,h=` + 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 = `+s+`(values, minMaxValue); + } + `,f="vec4";t==="all"?(i="1.0",h=` + bool reducedAllValue = all(values); + float floatedReducedAllValue = float(reducedAllValue); + allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0); + `,f="bvec4"):t==="any"&&(i="0.0",h=` + bool reducedAnyValue = any(values); + float floatedReducedAnyValue = float(reducedAnyValue); + anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0); + `,f="bvec4");var d="";o%e>0&&(d=` + if (inIdx < 0 || inIdx >= `+o+`) { + return initializationValue; + } + `),this.userCode=` + const float initializationValue = `+i+`; + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float getValue(int batch, int inIdx) { + `+d+` + return getX(batch, inIdx); + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = outIdx * `+e+`; + + vec4 minMaxValue = vec4(`+i+`); + float prodValue = 1.0; + float sumValue = 0.0; + float allValue = 1.0; + float anyValue = 0.0; + + for (int i = 0; i < `+c+`; i += 4) { + int inIdx = inOffset + i; + `+f+" values = "+f+`( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + getValue(batch, inIdx + 3) + ); + + `+h+` + } + + int inIdx = inOffset + `+c+`; + if (`+(l===1)+`) { + `+f+" values = "+f+`( + getValue(batch, inIdx), + initializationValue, + initializationValue, + initializationValue + ); + + `+h+` + } else if (`+(l===2)+`) { + `+f+" values = "+f+`( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + initializationValue, + initializationValue + ); + + `+h+` + } else if (`+(l===3)+`) { + `+f+" values = "+f+`( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + initializationValue + ); + + `+h+` + } + setOutput(`+u+`); + } + `},um=function(r,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r;for(var e="",n=0;n<4;n++){var o="thisRC = rc;";n%2==1&&(o+="thisRC.z += 1;"),n>1&&(o+="thisRC.y += 1;"),e+=` + `+o+` + `+(n>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[`+n+`] = + getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims); + `+(n>0?"}":"")+` + `}this.userCode=` + + ivec3 inputCoordsFromReshapedOutCoords(int index) { + `+En(["r","c","d"],t)+` + return ivec3(r, c, d); + } + + `+Li(r)+` + + void main() { + ivec3 rc = getOutputCoords(); + + vec4 result = vec4(0.); + + ivec3 thisRC; + int rows = `+r[1]+`; + int cols = `+r[2]+`; + + `+e+` + + setOutput(result); + } + `},cm=function(r,t,e){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var n=t.shape,o=n[1],a=n[2],i=r.shape,s=i[1],u=i[2],c=[e&&s>1?o-1:o,e&&u>1?a-1:a],l=[e&&s>1?s-1:s,e&&u>1?u-1:u],h=c[0]/l[0],f=c[1]/l[1],d=1/h,p=1/f,m=2*Math.ceil(d)+2,v=2*Math.ceil(p)+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(`+h+`); + const float widthScale = float(`+f+`); + + const float invHeightScale = float(`+d+`); + const float invWidthScale = float(`+p+`); + + const int winHeight = int(`+m+`); + const int winWidth = int(`+v+`); + + // 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 >= `+s+`) { + 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 >= `+u+`) { + continue; + } + + float dxR = float(dyR) * heightScale; + int topDxRIndex = int(floor(dxR)); + int bottomDxRIndex = int(min(ceil(dxR), `+(o-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), `+(a-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); + } + `},lm=function(r,t,e,n){this.variableNames=["A"],this.outputShape=[];var o=r[0],a=r[1],i=r[2],s=r[3];this.outputShape=[o,t,e,s];var u=[n&&t>1?a-1:a,n&&e>1?i-1:i],c=[n&&t>1?t-1:t,n&&e>1?e-1:e];this.userCode=` + const vec2 effectiveInputOverOutputRatioRC = vec2( + `+u[0]/c[0]+`, + `+u[1]/c[1]+`); + const vec2 inputShapeRC = vec2(`+a+".0, "+i+`.0); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + ivec2 yRC = coords.yz; + + // Fractional source index. + vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC; + + // Compute the four integer indices. + ivec2 sourceFloorRC = ivec2(sourceFracIndexRC); + 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); + } + `},hm=function(r,t,e,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var o=r[0],a=r[1],i=r[2],s=r[3];this.outputShape=[o,t,e,s];var u=[n&&t>1?a-1:a,n&&e>1?i-1:i],c=[n&&t>1?t-1:t,n&&e>1?e-1:e];this.userCode=` + const vec3 effectiveInputOverOutputRatioRC = vec3( + `+u[0]/c[0]+`, + `+u[1]/c[1]+`, + `+u[1]/c[1]+`); + const vec3 inputShapeRC = vec3(`+a+".0, "+i+`.0, + `+i+`.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 = vec3(yRC) * effectiveInputOverOutputRatioRC; + + // Compute the four integer indices. + ivec3 sourceFloorRC = ivec3(sourceFracIndexRC); + ivec3 sourceCeilRC = ivec3( + min(inputShapeRC - 1.0, ceil(sourceFracIndexRC))); + + // Should we calculate next column and row elements in 2x2 packed cell. + bool hasNextCol = d < `+(s-1)+`; + bool hasNextRow = coords.z < `+(e-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); + } + `},fm=function(r,t,e){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var n=t.shape,o=n[1],a=n[2],i=r.shape,s=i[1],u=i[2],c=[e&&s>1?o-1:o,e&&u>1?a-1:a],l=[e&&s>1?s-1:s,e&&u>1?u-1:u],h=c[0]/l[0],f=c[1]/l[1],d=1/h,p=1/f,m=2*Math.ceil(d)+2,v=2*Math.ceil(p)+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(`+h+`); + const float widthScale = float(`+f+`); + + const float invHeightScale = float(`+d+`); + const float invWidthScale = float(`+p+`); + + const int winHeight = int(`+m+`); + const int winWidth = int(`+v+`); + + // 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 >= `+s+`) { + 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 >= `+u+`) { + continue; + } + + float sourceFracRow = + float(`+c[0]+`) * + (float(dyR) / float(`+l[0]+`)); + + float sourceFracCol = + float(`+c[1]+`) * + (float(dyC) / float(`+l[1]+`)); + + int sourceNearestRow = int(min( + float(int(`+o+`) - 1), + `+e+` ? float(round(sourceFracRow)) : + float(floor(sourceFracRow)))); + + int sourceNearestCol = int(min( + float(int(`+a+`) - 1), + `+e+` ? float(round(sourceFracCol)) : + float(floor(sourceFracCol)))); + + if (r == sourceNearestRow && c == sourceNearestCol) { + accumulator += getDy(b, dyR, dyC, d); + } + } + } + // End loop over dy + + setOutput(accumulator); + } + `},dm=function(r,t,e,n){this.variableNames=["A"],this.outputShape=[];var o=r[0],a=r[1],i=r[2],s=r[3];this.outputShape=[o,t,e,s];var u=[n&&t>1?a-1:a,n&&e>1?i-1:i],c=[n&&t>1?t-1:t,n&&e>1?e-1:e],l=n?"0.5":"0.0";this.userCode=` + const vec2 effectiveInputOverOutputRatioRC = vec2( + `+u[0]/c[0]+`, + `+u[1]/c[1]+`); + const vec2 inputShapeRC = vec2(`+a+".0, "+i+`.0); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + ivec2 yRC = coords.yz; + + // Fractional source index. + vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC; + + // Compute the coordinators of nearest neighbor point. + ivec2 sourceNearestRC = ivec2( + min(inputShapeRC - 1.0, floor(sourceFracIndexRC + `+l+`))); + + float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d); + + setOutput(newValue); + } + `},pm=function(r,t){this.variableNames=["x"];var e=r.length;if(e>4)throw new Error("WebGL backend: Reverse of rank-"+e+" tensor is not yet supported");if(this.outputShape=r,e!==1){var n=r.map((function(a,i){return(function(s){return t.indexOf(s)!==-1&&r[s]!==1?r[s]+" - coords["+s+"] - 1":"coords["+s+"]"})(i)})).join(","),o=_e(e);this.userCode=` + void main() { + `+o+` coords = getOutputCoords(); + setOutput(getX(`+n+`)); + } + `}else this.userCode=` + void main() { + int coord = getOutputCoords(); + setOutput(getX(`+r[0]+` - coord - 1)); + } + `},vm=function(r,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var e=r.length;if(e>4)throw new Error("WebGL backend: Reverse of rank-"+e+" tensor is not yet supported");this.outputShape=r;var n=rt("rc",e),o=n[e-1]+" + 1 < "+this.outputShape[e-1],a=n[e-2]+" + 1 < "+this.outputShape[e-2],i=_e(e);function s(u){var c=r.map((function(l,h){return(function(f,d){return t.indexOf(f)!==-1&&r[f]!==1?r[f]+" - "+d[f]+" - 1":""+d[f]})(h,u)}));return"getChannel(getX("+c.join(",")+"), vec2("+c.slice(-2).join(",")+"))"}this.userCode=e===1?` + void main(){ + int rc = getOutputCoords(); + vec4 result = vec4(0.); + result.r = getChannel(getX(`+r[0]+` - rc - 1), + `+r[0]+` - rc - 1); + if(`+o+`){ + result.g = getChannel(getX(`+r[0]+` - (rc + 1) - 1), + `+r[0]+` - (rc + 1) - 1); + } + setOutput(result); + } + `:` + void main() { + `+i+` rc = getOutputCoords(); + vec4 result = vec4(0.); + result.r = `+(function(u){return s(u)})(n.slice())+`; + if(`+o+`){ + result.g = `+(function(u){return u[e-1]="("+u[e-1]+" + 1)",s(u)})(n.slice())+`; + } + if(`+a+`) { + result.b = `+(function(u){return u[e-2]="("+u[e-2]+" + 1)",s(u)})(n.slice())+`; + if(`+o+`) { + result.a = `+(function(u){return u[e-1]="("+u[e-1]+" + 1)",u[e-2]="("+u[e-2]+" + 1)",s(u)})(n.slice())+`; + } + } + setOutput(result); + } + `},du=function(r,t,e,n,o,a,i){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=_e(o.length),u=_e(a.length),c="";e===1?c="i":e===2&&(c="i, j");var l="getIndices("+c+")",h="";n===1?h="i":n===2&&(h="i, coords[1]");var f="getUpdates("+h+")",d=t>1?"strides[j]":"strides";this.userCode=` + `+s+" strides = "+s+"("+o+`); + + void main() { + `+u+` coords = getOutputCoords(); + float sum = 0.0; + bool found = false; + for (int i = 0; i < `+r+`; i++) { + int flattenedIndex = 0; + for (int j = 0; j < `+t+`; j++) { + int index = round(`+l+`); + flattenedIndex += index * `+d+`; + } + if (flattenedIndex == coords[0]) { + sum += `+f+`; + found = true; + } + } + setOutput(mix(getDefaultValue(), sum, float(found))); + } + `},mm=function(r,t){this.variableNames=["x","segmentIds"];var e=r.windowSize,n=r.batchSize,o=r.inSize,a=r.numSegments,i=a*Math.ceil(o/e);this.outputShape=[n,i];var s=4*Math.floor(e/4),u=e%4,c=` + sumValue += dot(values, segFilter); + `,l="";o%e>0&&(l=` + if (inIdx < 0 || inIdx >= `+o+`) { + return initializationValue; + } + `);var h="";o%e>0&&(h=` + if (inIdx < 0 || inIdx >= `+o+`) { + return -1.0; + } + `),this.userCode=` + const float initializationValue = 0.0; + + float getValue(int batch, int inIdx) { + `+l+` + return getX(batch, inIdx); + } + + float getSegmentIdAtIndex(int inIdx) { + `+h+` + return getSegmentIds(inIdx); + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = int(floor(float(outIdx) / float( + `+a+")) * float("+e+`)); + int currentSeg = int(mod(float(outIdx), float(`+a+`))); + + float sumValue = 0.0; + + for (int i = 0; i < `+s+`; 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 + ); + + `+c+` + } + + int inIdx = inOffset + `+s+`; + if (`+(u===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 + ); + + `+c+` + } else if (`+(u===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 + ); + + `+c+` + } else if (`+(u===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 + ); + + `+c+` + } + setOutput(sumValue); + } + `},gm=function(r,t,e){var n,o;if(this.variableNames=["c","a","b"],this.outputShape=t,e>4)throw Error("Where for rank "+e+" is not yet supported");if(e===1)o="resRC",n="resRC";else{for(var a=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],u=0;u= 1.0) { + setOutput(getA(`+o+`)); + } else { + setOutput(getB(`+o+`)); + } + } + `},ym=(function(){function r(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=_e(this.rank),o="uniform int start["+this.rank+"];",a=(function(i){if(i===1)return"sourceLoc";if(i<=6)return xa.slice(0,i).map((function(s){return"sourceLoc."+s})).join(",");throw Error("Slicing for rank "+i+" is not yet supported")})(this.rank);e=` + `+n+` sourceLoc; + `+n+` coords = getOutputCoords(); + `+t.map((function(i,s){return"sourceLoc."+xa[s]+" = start["+s+"] + coords."+xa[s]+";"})).join(` +`)+` + `,this.userCode=` + `+o+` + void main() { + `+e+` + setOutput(getSource(`+a+`)); + } + `}return r.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,o){e.startLoc==null&&(e.startLoc=n.getUniformLocationNoThrow(o,"start"),e.startLoc==null)||n.gl.uniform1iv(e.startLoc,t)}},r})(),xa=["x","y","z","w","u","v"],xm=(function(){function r(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=_e(this.rank),n=rt("coords",this.rank),o=rt("sourceLoc",this.rank),a=this.rank===1?"sourceLoc":"vec2("+o.slice(-2).join()+")",i="getChannel(getSource("+o.join()+"), "+a+")",s=` + result.x = `+i+`; + if (++`+n[this.rank-1]+" < "+t[this.rank-1]+`) { + ++`+o[this.rank-1]+`; + result.y = `+i+`; + --`+o[this.rank-1]+`; + } + `,u=this.rank===1?"":` + --`+n[this.rank-1]+`; + if (++`+n[this.rank-2]+" < "+t[this.rank-2]+`) { + ++`+o[this.rank-2]+`; + result.z = `+i+`; + if (++`+n[this.rank-1]+" < "+t[this.rank-1]+`) { + ++`+o[this.rank-1]+`; + result.w = `+i+`; + } + } + `,c=this.rank<=4?`sourceLoc = coords + + `+e+"("+t.map((function(l,h){return"start["+h+"]"})).join()+");":t.map((function(l,h){return o[h]+" = "+n[h]+" + start["+h+"];"})).join(` +`);this.userCode=` + uniform int start[`+this.rank+`]; + void main() { + `+e+` coords = getOutputCoords(); + `+e+` sourceLoc; + `+c+` + vec4 result = vec4(0.); + `+s+` + `+u+` + setOutput(result); + } + `}return r.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,o){e.startLoc==null&&(e.startLoc=n.getUniformLocationNoThrow(o,"start"),e.startLoc==null)||n.gl.uniform1iv(e.startLoc,t)}},r})(),bm=function(r,t,e){this.variableNames=["x"],this.outputShape=e;var n=e.length,o=_e(e.length),a=_e(e.length),i="";if(n===1)i="coords * strides + begin";else{var s=0;i=e.map((function(u,c){return s++,e.length===1?"coords * strides["+c+"] + begin["+c+"]":"coords["+(s-1)+"] * strides["+c+"] + begin["+c+"]"})).join(",")}this.userCode=` + `+o+" begin = "+o+"("+r+`); + `+o+" strides = "+o+"("+t+`); + + void main() { + `+a+` coords = getOutputCoords(); + setOutput(getX(`+i+`)); + } + `},wm=(function(){function r(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return r.prototype.acquireTexture=function(t,e,n){var o,a=pu(e,n),i=vu(t,a,n);if(i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]),this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var s=this.freeTextures[i].shift();return this.usedTextures[i].push(s),s}return this.numUsedTextures++,this.log(),a===it.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):a===it.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):a===it.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):a===it.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):a===it.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[i].push(o),o},r.prototype.releaseTexture=function(t,e,n,o){if(this.freeTextures!=null){var a=vu(e,pu(n,o),o);a in this.freeTextures||(this.freeTextures[a]=[]),this.freeTextures[a].push(t),this.numFreeTextures++,this.numUsedTextures--;var i=this.usedTextures[a],s=i.indexOf(t);if(s<0)throw new Error("Cannot release a texture that was never provided by this texture manager");i.splice(s,1),this.log()}},r.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},r.prototype.getNumUsedTextures=function(){return this.numUsedTextures},r.prototype.getNumFreeTextures=function(){return this.numFreeTextures},r.prototype.dispose=function(){var t=this;if(this.freeTextures!=null){for(var e in this.freeTextures)this.freeTextures[e].forEach((function(n){t.gpgpu.deleteMatrixTexture(n)}));for(var e in this.usedTextures)this.usedTextures[e].forEach((function(o){t.gpgpu.deleteMatrixTexture(o)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},r})();function pu(r,t){if(r===ct.UPLOAD)return it.PACKED_2X2_FLOAT32;if(r===ct.RENDER||r==null)return(function(e){return M().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?it.PACKED_2X2_FLOAT32:it.UNPACKED_FLOAT32:e?it.PACKED_2X2_FLOAT16:it.UNPACKED_FLOAT16})(t);if(r===ct.DOWNLOAD||r===ct.PIXELS)return it.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+r)}function vu(r,t,e){return r[0]+"_"+r[1]+"_"+t+"_"+e}var Cm=function(r,t){this.variableNames=["A"];for(var e=new Array(r.length),n=0;n5)throw Error("Tile for rank "+s+" is not yet supported");if(s===1)return"imod(resRC, "+i[0]+")";for(var u=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],c=[],l=0;l6)throw Error("Transpose for rank "+s+" is not yet supported");for(var u=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],c=new Array(s),l=0;l6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var o=_e(this.rank),a=yl("rc",this.rank),i=new Array(this.rank);for(n=0;n= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0); +`,gu="return -x;",yu="return ceil(x);",xu="return floor(x);",bu="return exp(x);",wu="return exp(x) - 1.0;",km=Rt+` + return sin(x); +`,Sm=Rt+` + return cos(x); +`,Am=Rt+` + if (abs(x) > 1.) { + return NAN; + } + return asin(x); +`,Dm=Rt+` + if (abs(x) > 1.) { + return NAN; + } + return acos(x); +`,Tm=Rt+` + return atan(x); +`,Fm=Rt+"return log(x + sqrt(x * x + 1.0));",Nm=Rt+` + if (x < 1.0) return NAN; + return log(x + sqrt(x * x - 1.0));`,Pm=Rt+` + if ((x < -1.0) || (x > 1.0)) return NAN; + return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,Qr="return x;",Mm="return x;",Gl=` + 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; +`,Hl=` + 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; +`,ql=` + 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; +`,dr=function(r,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r,this.userCode=` + vec4 unaryOperation(vec4 x) { + `+t+` + } + + void main() { + vec4 x = getAAtOutCoords(); + vec4 y = unaryOperation(x); + + setOutput(y); + } + `},Om=function(r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=r;var t=r.length,e=rt("rc",t),n=_e(t),o=(function(s,u){if(s===1)return"rc";for(var c="",l=0;l0?[4,Promise.all(i)]:[3,2];case 1:return c=l.sent(),u.kernelMs=ju(c),u.getExtraProfileInfo=function(){return c.map((function(h,f){return{name:s[f],ms:h}})).map((function(h){return h.name+": "+h.ms})).join(", ")},[3,3];case 2:u.kernelMs={error:"WebGL query timers are not supported in this environment."},l.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,u]}}))}))},t.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},t.prototype.startTimer=function(){return M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:gt(),endMs:null}},t.prototype.endTimer=function(e){return M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=gt(),e)},t.prototype.getQueryTime=function(e){return J(this,void 0,void 0,(function(){var n;return Q(this,(function(o){return M().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(n=e).endMs-n.startMs]}))}))},t.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e)){if(this.pendingRead.has(e))return this.pendingDisposal.add(e),void this.pendingDeletes++;if(this.texData.has(e)){this.releaseGPUData(e);var n=this.texData.get(e).complexTensors;n!=null&&(n.real.dispose(),n.imag.dispose()),this.texData.delete(e)}}},t.prototype.releaseGPUData=function(e){var n=this.texData.get(e),o=n.texture,a=n.dtype,i=n.texShape,s=n.usage,u=n.isPacked,c=n.slice,l=c&&c.origDataId||e,h=this.dataRefCount.get(l);h>1?this.dataRefCount.set(l,h-1):(this.dataRefCount.delete(l),o!=null&&(this.numBytesInGPU-=this.computeBytes(i,a),this.textureManager.releaseTexture(o,i,s,u)));var f=this.texData.get(e);f.texture=null,f.texShape=null,f.isPacked=!1,f.slice=null},t.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},t.prototype.getDataInfo=function(e){return this.texData.get(e)},t.prototype.getCPUBackend=function(){return M().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=A.findBackend("cpu")),this.cpuBackend):null},t.prototype.shouldExecuteOnCPU=function(e,n){var o=this;return n===void 0&&(n=128),this.getCPUBackend()!=null&&e.every((function(a){return o.texData.get(a.dataId).texture==null&&a.sizeM().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var i=Math.floor(e.length/2),s=this.concat(e.slice(0,i),n),u=this.concat(e.slice(i),n);return this.concat([s,u],n)}if(M().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){var c=new Rv(e.map((function(d){return d.shape})),n);return this.compileAndRun(c,e)}var l=Dn(e.map((function(d){return d.shape})),n),h=e.map((function(d){return d.as2D(-1,Z(d.shape.slice(n)))})),f=new Iv(h.map((function(d){return d.shape})));return this.compileAndRun(f,h).reshape(l)},t.prototype.neg=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.neg(e);if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,gu,e.dtype);var n=new ae(e.shape,gu);return this.compileAndRun(n,[e])},t.prototype.batchMatMul=function(e,n,o,a){var i=o?e.shape[2]:e.shape[1],s=a?n.shape[1]:n.shape[2],u=o?e.shape[1]:e.shape[2],c=e.shape[0];if((i===1||s===1)&&u>1e3){o&&(e=e.transpose([0,2,1])),a&&(n=n.transpose([0,2,1]));var l=s===1?e:e.as3D(c,u,1),h=s===1?2:1,f=s===1?n.as3D(c,1,u):n;return this.multiply(l,f).sum(h,!0)}var d=Ve(e.dtype,n.dtype),p=new ma(e.shape,[c,i,s],o,a);return this.compileAndRun(p,[e,n],d)},t.prototype.fusedBatchMatMul=function(e){var n=e.a,o=e.b,a=e.transposeA,i=e.transposeB,s=e.bias,u=e.activation,c=e.preluActivationWeights,l=a?n.shape[2]:n.shape[1],h=i?o.shape[1]:o.shape[2],f=n.shape[0],d=Ve(n.dtype,o.dtype),p=s!=null,m=c!=null,v=u?eo(u,!0):null,g=new ma(n.shape,[f,l,h],a,i,p,v,m),x=[n,o];return s&&x.push(s),c&&x.push(c),this.compileAndRun(g,x,d)},t.prototype.multiply=function(e,n){if(e.dtype==="complex64"){var o=this.texData.get(e.dataId),a=this.texData.get(n.dataId),i=new au(bv,e.shape,n.shape),s=new au(wv,e.shape,n.shape),u=[this.makeComplexComponentTensorInfo(e,o.complexTensors.real),this.makeComplexComponentTensorInfo(e,o.complexTensors.imag),this.makeComplexComponentTensorInfo(n,a.complexTensors.real),this.makeComplexComponentTensorInfo(n,a.complexTensors.imag)],c=this.compileAndRun(i,u),l=this.compileAndRun(s,u),h=this.complex(c,l);return c.dispose(),l.dispose(),h}if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.multiply(e,n);if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,iu,e.dtype);var f=new Ae(iu,e.shape,n.shape);return this.compileAndRun(f,[e,n],e.dtype)},t.prototype.batchNormalization=function(e,n,o,a,i,s){var u=[e,n,o],c=null;s!=null&&(c=s.shape,u.push(s));var l=null;if(i!=null&&(l=i.shape,u.push(i)),M().getBool("WEBGL_PACK_NORMALIZATION")){var h=new xv(e.shape,n.shape,o.shape,c,l,a);return this.compileAndRun(h,u)}var f=new yv(e.shape,n.shape,o.shape,c,l,a);return this.compileAndRun(f,u)},t.prototype.localResponseNormalization4D=function(e,n,o,a,i){var s=M().getBool("WEBGL_PACK_NORMALIZATION")?new Zv(e.shape,n,o,a,i):new Jv(e.shape,n,o,a,i);return this.compileAndRun(s,[e])},t.prototype.LRNGrad=function(e,n,o,a,i,s,u){var c=new Qv(n.shape,a,i,s,u);return this.compileAndRun(c,[n,o,e])},t.prototype.tile=function(e,n){if(e.dtype==="string"){var o=this.readSync(e.dataId).map((function(i){return Cr(i)}));return ml(re(e.shape,e.dtype,o),n)}var a=new Cm(e.shape,n);return this.compileAndRun(a,[e])},t.prototype.pad=function(e,n,o){var a=M().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new im(e.shape,n,o):new am(e.shape,n,o);return this.compileAndRun(a,[e])},t.prototype.transpose=function(e,n){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.transpose(e,n);var o=M().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Em(e.shape,n):new _m(e.shape,n);return this.compileAndRun(o,[e])},t.prototype.gather=function(e,n,o){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.gather(e,n,o);var a=new Kv(e.shape,n.size,o);return this.compileAndRun(a,[e,n])},t.prototype.batchToSpaceND=function(e,n,o){E(e.rank<=4,(function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"}));var a=n.reduce((function(h,f){return h*f})),i=wo(e.shape,n,a),s=Co(i.length,n.length),u=_o(e.shape,n,a),c=al(o,n.length),l=il(u,o,n.length);return e.reshape(i).transpose(s).reshape(u).slice(c,l)},t.prototype.spaceToBatchND=function(e,n,o){E(e.rank<=4,(function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"}));var a=n.reduce((function(f,d){return f*d})),i=[[0,0]];i.push.apply(i,o);for(var s=1+n.length;sd||p===f?m=!0:p=yo(f,p+1);return p})(u,i),l=new mm({windowSize:c,inSize:u,batchSize:s,numSegments:i}),h=this.compileAndRun(l,[e,o],a);return h.shape[1]===i?h:(o=kr(0,i).tile([u/c]),this.segOpCompute(h,n,o,a,i))},t.prototype.argMinMaxReduce=function(e,n,o){var a=[n];if(nt("arg"+o.charAt(0).toUpperCase()+o.slice(1),a,e.rank),!M().getBool("WEBGL_PACK_REDUCE")||e.rank<=2){var i=qe(e.shape,a),s=i[0],u=Z(i[1]),c=e.as2D(-1,u);return this.argReduce(c,o).reshape(s)}return this.argReducePacked(e,o)},t.prototype.argMin=function(e,n){return this.argMinMaxReduce(e,n,"min")},t.prototype.argMax=function(e,n){return this.argMinMaxReduce(e,n,"max")},t.prototype.cumsum=function(e,n,o,a){if(n!==e.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(e.rank-1)+" but got axis="+n);var i=new Mv(e.shape,o,a);return this.compileAndRun(i,[e])},t.prototype.equal=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` + return vec4(equal(a, b)); +`,"bool");var o=new Ae("return float(a == b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.notEqual=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` + return vec4(notEqual(a, b)); +`,"bool");var o=new Ae("return float(a != b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.less=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.less(e,n);if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` + return vec4(lessThan(a, b)); +`,"bool");var o=new Ae("return float(a < b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.lessEqual=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` + return vec4(lessThanEqual(a, b)); +`,"bool");var o=new Ae("return float(a <= b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.greater=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.greater(e,n);if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` + return vec4(greaterThan(a, b)); +`,"bool");var o=new Ae("return float(a > b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.greaterEqual=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` + return vec4(greaterThanEqual(a, b)); +`,"bool");var o=new Ae("return float(a >= b);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.logicalNot=function(e){var n=new ae(e.shape,"return float(!(x >= 1.0));");return this.compileAndRun(n,[e])},t.prototype.logicalAnd=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` + return vec4( + vec4(greaterThanEqual(a, vec4(1.0))) * + vec4(greaterThanEqual(b, vec4(1.0)))); +`,"bool");var o=new Ae("return float(a >= 1.0 && b >= 1.0);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.logicalOr=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` + return min( + vec4(greaterThanEqual(a, vec4(1.0))) + + vec4(greaterThanEqual(b, vec4(1.0))), + vec4(1.0)); +`,"bool");var o=new Ae("return float(a >= 1.0 || b >= 1.0);",e.shape,n.shape);return this.compileAndRun(o,[e,n],"bool")},t.prototype.select=function(e,n,o){var a=new gm(e.rank,n.shape,n.rank);return this.compileAndRun(a,[e,n,o],Ve(n.dtype,o.dtype))},t.prototype.where=function(e){xo("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var n=e.dataSync();return Bi(e.shape,n)},t.prototype.topk=function(e,n,o){return gl(e.dataSync(),e.shape,e.dtype,n)},t.prototype.min=function(e,n){nt("min",n,e.rank);var o=qe(e.shape,n),a=o[0],i=Z(o[1]),s=e.as2D(-1,i);return this.reduce(s,"min",s.dtype).reshape(a)},t.prototype.minimum=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.minimum(e,n);var o=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Gt(` + vec4 result = vec4(min(a, b)); + vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); + + result.r = isNaN.r > 0. ? NAN : result.r; + result.g = isNaN.g > 0. ? NAN : result.g; + result.b = isNaN.b > 0. ? NAN : result.b; + result.a = isNaN.a > 0. ? NAN : result.a; + + return result; +`,e.shape,n.shape):new Ae(` + if (isnan(a)) return a; + if (isnan(b)) return b; + + return min(a, b); +`,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.mod=function(e,n){var o=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Gt(` + vec4 result = mod(a, b); + vec4 isNaN = vec4(equal(b, vec4(0.0))); + + result.r = isNaN.r > 0. ? NAN : result.r; + result.g = isNaN.g > 0. ? NAN : result.g; + result.b = isNaN.b > 0. ? NAN : result.b; + result.a = isNaN.a > 0. ? NAN : result.a; + + return result; +`,e.shape,n.shape):new Ae(`if (b == 0.0) return NAN; + return mod(a, b);`,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.max=function(e,n){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.max(e,n);nt("max",n,e.rank);var o=qe(e.shape,n),a=o[0],i=Z(o[1]),s=e.as2D(-1,i);return this.reduce(s,"max",s.dtype).reshape(a)},t.prototype.maximum=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.maximum(e,n);var o=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Gt(` + vec4 result = vec4(max(a, b)); + vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); + + result.r = isNaN.r > 0. ? NAN : result.r; + result.g = isNaN.g > 0. ? NAN : result.g; + result.b = isNaN.b > 0. ? NAN : result.b; + result.a = isNaN.a > 0. ? NAN : result.a; + + return result; +`,e.shape,n.shape):new Ae(` + if (isnan(a)) return a; + if (isnan(b)) return b; + + return max(a, b); +`,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.all=function(e,n){nt("all",n,e.rank);var o=qe(e.shape,n),a=o[0],i=Z(o[1]),s=e.as2D(-1,i);return this.reduce(s,"all",s.dtype).reshape(a)},t.prototype.any=function(e,n){nt("any",n,e.rank);var o=qe(e.shape,n),a=o[0],i=Z(o[1]),s=e.as2D(-1,i);return this.reduce(s,"any",s.dtype).reshape(a)},t.prototype.realDivide=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` + // 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; +`,"float32",!0);var o=new Ae(` +if (a == b) { + return 1.0; +}; +return a / b;`,e.shape,n.shape);return this.compileAndRun(o,[e,n],"float32")},t.prototype.floorDiv=function(e,n){if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,` + 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); +`,"int32");var o=new Ae(` + 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; + } +`,e.shape,n.shape);return this.compileAndRun(o,[e,n],"int32")},t.prototype.add=function(e,n){if(e.dtype==="complex64"&&n.dtype==="complex64")return this.complexSeparableBinaryOp(e,n,pa);if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.add(e,n);var o=Ve(e.dtype,n.dtype);if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,pa,o);var a=new Ae(pa,e.shape,n.shape);return this.compileAndRun(a,[e,n],o)},t.prototype.packedUnaryOp=function(e,n,o){var a=new dr(e.shape,n);return this.compileAndRun(a,[e],o)},t.prototype.packedBinaryOp=function(e,n,o,a,i){i===void 0&&(i=!1);var s=new Gt(o,e.shape,n.shape,i);return this.compileAndRun(s,[e,n],a)},t.prototype.complexSeparableBinaryOp=function(e,n,o){var a=this,i=this.texData.get(e.dataId),s=this.texData.get(n.dataId),u=[[i.complexTensors.real,s.complexTensors.real],[i.complexTensors.imag,s.complexTensors.imag]].map((function(f){var d=f[0],p=f[1],m=a.makeComplexComponentTensorInfo(e,d),v=a.makeComplexComponentTensorInfo(n,p),g=new Ae(o,e.shape,n.shape);return a.compileAndRun(g,[m,v],Ve(d.dtype,p.dtype))})),c=u[0],l=u[1],h=this.complex(c,l);return c.dispose(),l.dispose(),h},t.prototype.makeComplexComponentTensorInfo=function(e,n){return{dataId:n.dataId,dtype:n.dtype,shape:e.shape}},t.prototype.addN=function(e){if(e.length===1)return e[0];if(e.length>M().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var n=Math.floor(e.length/2),o=this.addN(e.slice(0,n)),a=this.addN(e.slice(n));return this.addN([o,a])}var i=e.map((function(c){return c.dtype})).reduce((function(c,l){return Ve(c,l)})),s=e.map((function(c){return c.shape})),u=M().getBool("WEBGL_PACK")?new uv(e[0].shape,s):new sv(e[0].shape,s);return this.compileAndRun(u,e,i)},t.prototype.subtract=function(e,n){if(e.dtype==="complex64"&&n.dtype==="complex64")return this.complexSeparableBinaryOp(e,n,va);if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.subtract(e,n);var o=Ve(e.dtype,n.dtype);if(M().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,va,e.dtype);var a=new Ae(va,e.shape,n.shape);return this.compileAndRun(a,[e,n],o)},t.prototype.pow=function(e,n){var o=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Gt(` + // 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; + + vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b)); + + result.r = isNaN.r > 0. ? NAN : result.r; + result.g = isNaN.g > 0. ? NAN : result.g; + result.b = isNaN.b > 0. ? NAN : result.b; + result.a = isNaN.a > 0. ? NAN : result.a; + + return result; +`,e.shape,n.shape):new Ae(` +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); +`,e.shape,n.shape),a=Ve(e.dtype,n.dtype);return this.compileAndRun(o,[e,n],a)},t.prototype.ceil=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.ceil(e);if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,yu,e.dtype);var n=new ae(e.shape,yu);return this.compileAndRun(n,[e])},t.prototype.floor=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.floor(e);if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,xu,e.dtype);var n=new ae(e.shape,xu);return this.compileAndRun(n,[e])},t.prototype.sign=function(e){var n=new ae(e.shape,` + if (isnan(x)) { return 0.0; } + return sign(x); +`);return this.compileAndRun(n,[e])},t.prototype.isNaN=function(e){var n=new ae(e.shape,"return float(isnan(x));");return this.compileAndRun(n,[e],"bool")},t.prototype.isInf=function(e){var n=new ae(e.shape,"return float(isinf(x));");return this.compileAndRun(n,[e],"bool")},t.prototype.isFinite=function(e){var n=new ae(e.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(n,[e],"bool")},t.prototype.round=function(e){var n=new ae(e.shape,` + // 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; + } + } +`);return this.compileAndRun(n,[e])},t.prototype.exp=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.exp(e);if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,bu,e.dtype);var n=new ae(e.shape,bu);return this.compileAndRun(n,[e])},t.prototype.expm1=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.expm1(e);if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,wu,e.dtype);var n=new ae(e.shape,wu);return this.compileAndRun(n,[e])},t.prototype.softmax=function(e,n){var o=Le([n],e.shape),a=this.max(e,o),i=et(a.shape,o),s=this.subtract(e,a.reshape(i)),u=this.exp(s),c=this.sum(u,o).reshape(i);return this.realDivide(u,c)},t.prototype.log=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.log(e);if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,` + vec4 result = log(x); + vec4 isNaN = vec4(lessThan(x, vec4(0.0))); + result.r = isNaN.r == 1.0 ? NAN : result.r; + result.g = isNaN.g == 1.0 ? NAN : result.g; + result.b = isNaN.b == 1.0 ? NAN : result.b; + result.a = isNaN.a == 1.0 ? NAN : result.a; + + return result; +`,e.dtype);var n=new ae(e.shape,`if (x < 0.0) return NAN; + return log(x);`);return this.compileAndRun(n,[e])},t.prototype.log1p=function(e){var n=new ae(e.shape,"return log(1.0 + x);");return this.compileAndRun(n,[e])},t.prototype.sqrt=function(e){var n=new ae(e.shape,"return sqrt(x);");return this.compileAndRun(n,[e])},t.prototype.rsqrt=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.rsqrt(e);var n=new ae(e.shape,"return inversesqrt(x);");return this.compileAndRun(n,[e])},t.prototype.reciprocal=function(e){var n=new ae(e.shape,"return 1.0 / x;");return this.compileAndRun(n,[e])},t.prototype.relu=function(e){var n;return n=M().getBool("WEBGL_PACK")?new dr(e.shape,Gl):new ae(e.shape,zl),this.compileAndRun(n,[e])},t.prototype.relu6=function(e){var n;return n=M().getBool("WEBGL_PACK")?new dr(e.shape,Hl):new ae(e.shape,Ul),this.compileAndRun(n,[e])},t.prototype.prelu=function(e,n){var o=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Gt(Cl,e.shape,n.shape):new Ae(wl,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.elu=function(e){if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,ql,e.dtype);var n=new ae(e.shape,Vl);return this.compileAndRun(n,[e])},t.prototype.eluDer=function(e,n){var o=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Gt(` + vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.))); + return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0)))); +`,e.shape,n.shape):new Ae("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.selu=function(e){var n=new ae(e.shape,Rm);return this.compileAndRun(n,[e])},t.prototype.int=function(e){var n=new ae(e.shape,"return float(int(x));");return this.compileAndRun(n,[e],"int32")},t.prototype.clip=function(e,n,o){var a,i=(a=M().getBool("WEBGL_PACK_CLIP")?new _v(e.shape):new Cv(e.shape)).getCustomSetupFunc(n,o);return this.compileAndRun(a,[e],null,i)},t.prototype.abs=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.abs(e);if(M().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,mu,e.dtype);var n=new ae(e.shape,mu);return this.compileAndRun(n,[e])},t.prototype.complexAbs=function(e){var n=this.texData.get(e.dataId),o=new Ev(e.shape),a=[this.makeComplexComponentTensorInfo(e,n.complexTensors.real),this.makeComplexComponentTensorInfo(e,n.complexTensors.imag)];return this.compileAndRun(o,a)},t.prototype.sigmoid=function(e){var n=new ae(e.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(n,[e])},t.prototype.softplus=function(e){var n=new ae(e.shape,` + 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; +`);return this.compileAndRun(n,[e])},t.prototype.sin=function(e){var n=new ae(e.shape,km);return this.compileAndRun(n,[e])},t.prototype.cos=function(e){var n=new ae(e.shape,Sm);return this.compileAndRun(n,[e])},t.prototype.tan=function(e){var n=new ae(e.shape,"return tan(x);");return this.compileAndRun(n,[e])},t.prototype.asin=function(e){var n=new ae(e.shape,Am);return this.compileAndRun(n,[e])},t.prototype.acos=function(e){var n=new ae(e.shape,Dm);return this.compileAndRun(n,[e])},t.prototype.atan=function(e){var n=new ae(e.shape,Tm);return this.compileAndRun(n,[e])},t.prototype.atan2=function(e,n){var o=M().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Gt(` + vec4 result = atan(a, b); + vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); + + result.r = isNaN.r > 0. ? NAN : result.r; + result.g = isNaN.g > 0. ? NAN : result.g; + result.b = isNaN.b > 0. ? NAN : result.b; + result.a = isNaN.a > 0. ? NAN : result.a; + + return result; +`,e.shape,n.shape):new Ae(` + if (isnan(a)) return a; + if (isnan(b)) return b; + + return atan(a, b); +`,e.shape,n.shape);return this.compileAndRun(o,[e,n])},t.prototype.sinh=function(e){var n=new ae(e.shape,` + float e2x = exp(x); + return (e2x - 1.0 / e2x) / 2.0; +`);return this.compileAndRun(n,[e])},t.prototype.cosh=function(e){var n=new ae(e.shape,` + float e2x = exp(-x); + return (e2x + 1.0 / e2x) / 2.0; +`);return this.compileAndRun(n,[e])},t.prototype.tanh=function(e){var n=new ae(e.shape,` + float e2x = exp(-2.0 * abs(x)); + return sign(x) * (1.0 - e2x) / (1.0 + e2x); +`);return this.compileAndRun(n,[e])},t.prototype.asinh=function(e){var n=new ae(e.shape,Fm);return this.compileAndRun(n,[e])},t.prototype.acosh=function(e){var n=new ae(e.shape,Nm);return this.compileAndRun(n,[e])},t.prototype.atanh=function(e){var n=new ae(e.shape,Pm);return this.compileAndRun(n,[e])},t.prototype.erf=function(e){var n=new ae(e.shape,` + // Error function is calculated approximately with elementary function. + // See "Handbook of Mathematical Functions with Formulas, + // Graphs, and Mathematical Tables", Abramowitz and Stegun. + float p = 0.3275911; + float a1 = 0.254829592; + float a2 = -0.284496736; + float a3 = 1.421413741; + float a4 = -1.453152027; + float a5 = 1.061405429; + + 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)); +`);return this.compileAndRun(n,[e])},t.prototype.step=function(e,n){var o=new ae(e.shape,(function(a){return a===void 0&&(a=0),Rt+` + return x > 0.0 ? 1.0 : float(`+a+`); + `})(n));return this.compileAndRun(o,[e])},t.prototype.conv2dByMatMul=function(e,n,o,a,i,s){var u=e.shape,c=this.texData.get(e.dataId),l=o.inChannels,h=u[0]*u[1]*u[2],f=o.outChannels,d=o.dataFormat==="channelsLast",p=(h===1||f===1)&&l>1e3,m=u[2]%2!=0&&!!c.isPacked;if(p||!M().getBool("WEBGL_LAZILY_UNPACK")||!M().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!m){var v=d?u[0]*u[1]*u[2]:u[0]*u[2]*u[3],g=this.reshape(e,[1,v,o.inChannels]),x=this.reshape(n,[1,o.inChannels,o.outChannels]);return this.reshape(this.fusedBatchMatMul({a:g,b:x,transposeA:!1,transposeB:!1,bias:a,activation:i,preluActivationWeights:s}),o.outShape)}var b=d?u[0]*u[1]*(u[2]+1):u[0]*u[2]*(u[3]+1),y={dataId:e.dataId,shape:[1,b,o.inChannels],dtype:e.dtype},w=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,E(mr(c.shape,y.shape),(function(){return"packed reshape "+c.shape+" to "+y.shape+" isn't free"}));var _=this.reshape(n,[1,o.inChannels,o.outChannels]),S=this.fusedBatchMatMul({a:y,b:_,transposeA:!1,transposeB:!1,bias:a,activation:i,preluActivationWeights:s}),k=this.texData.get(S.dataId);return E(k.isPacked,(function(){return"batchMatMul result is expected to be packed"})),c.shape=w,k.shape=o.outShape,A.makeTensorFromDataId(S.dataId,o.outShape,S.dtype)},t.prototype.conv2dWithIm2Row=function(e,n,o,a,i,s){var u=o.filterWidth,c=o.filterHeight,l=o.inChannels,h=o.outWidth,f=o.outHeight,d=o.dataFormat==="channelsLast",p=u*c*l,m=f*h,v=[p,m],g=e.squeeze([0]),x=n.reshape([1,p,-1]),b=new $v(v,g.shape,o),y=this.compileAndRun(b,[g]).reshape([1,v[0],v[1]]),w=a!=null,_=s!=null,S=i?eo(i,!0):null,k=new ma(y.shape,[1,m,o.outChannels],!0,!1,w,S,_),I=[y,x];a&&I.push(a),_&&I.push(s);var R=this.compileAndRun(k,I);return d?R.reshape([1,f,h,o.outChannels]):R.reshape([1,o.outChannels,f,h])},t.prototype.fusedConv2d=function(e){var n=e.input,o=e.filter,a=e.convInfo,i=e.bias,s=e.activation,u=e.preluActivationWeights;if(a.filterHeight===1&&a.filterWidth===1&&a.dilationHeight===1&&a.dilationWidth===1&&a.strideHeight===1&&a.strideWidth===1&&(a.padInfo.type==="SAME"||a.padInfo.type==="VALID"))return this.conv2dByMatMul(n,o,a,i,s,u);if(M().getBool("WEBGL_CONV_IM2COL")&&n.shape[0]===1)return this.conv2dWithIm2Row(n,o,a,i,s,u);var c=i!=null,l=u!=null,h=s?eo(s,!1):null,f=new su(a,c,h,l),d=[n,o];return i&&d.push(i),u&&d.push(u),this.compileAndRun(f,d)},t.prototype.conv2d=function(e,n,o){if(o.filterHeight===1&&o.filterWidth===1&&o.dilationHeight===1&&o.dilationWidth===1&&o.strideHeight===1&&o.strideWidth===1&&(o.padInfo.type==="SAME"||o.padInfo.type==="VALID"))return this.conv2dByMatMul(e,n,o);if(M().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,n,o);var a=new su(o);return this.compileAndRun(a,[e,n])},t.prototype.conv2dDerInput=function(e,n,o){var a=new Sv(o);return this.compileAndRun(a,[e,n])},t.prototype.conv2dDerFilter=function(e,n,o){var a=new kv(o);return this.compileAndRun(a,[e,n])},t.prototype.fusedDepthwiseConv2D=function(e){var n,o=e.input,a=e.filter,i=e.convInfo,s=e.bias,u=e.activation,c=e.preluActivationWeights,l=M().getBool("WEBGL_PACK_DEPTHWISECONV")&&i.strideWidth<=2&&i.outChannels/i.inChannels==1,h=u?eo(u,l):null,f=[o,a],d=s!=null,p=c!=null;return d&&f.push(s),p&&f.push(c),l?(n=new cu(i,d,h,p),this.compileAndRun(n,f)):(n=new uu(i,d,h,p),this.compileAndRun(n,f))},t.prototype.depthwiseConv2D=function(e,n,o){var a;return M().getBool("WEBGL_PACK_DEPTHWISECONV")&&o.strideWidth<=2&&o.outChannels/o.inChannels==1?(a=new cu(o),this.compileAndRun(a,[e,n])):(a=new uu(o),this.compileAndRun(a,[e,n]))},t.prototype.depthwiseConv2DDerInput=function(e,n,o){var a=new Fv(o);return this.compileAndRun(a,[e,n])},t.prototype.depthwiseConv2DDerFilter=function(e,n,o){var a=new Tv(o);return this.compileAndRun(a,[e,n])},t.prototype.conv3d=function(e,n,o){var a=new Nv(o);return this.compileAndRun(a,[e,n])},t.prototype.conv3dDerInput=function(e,n,o){var a=new Dv(o);return this.compileAndRun(a,[e,n])},t.prototype.conv3dDerFilter=function(e,n,o){var a=new Av(o);return this.compileAndRun(a,[e,n])},t.prototype.maxPool=function(e,n){var o=new ga(n,"max",!1);return this.compileAndRun(o,[e])},t.prototype.avgPool=function(e,n){var o=new ga(n,"avg",!1);return this.compileAndRun(o,[e],"float32")},t.prototype.maxPoolBackprop=function(e,n,o,a){var i=new ga(a,"max",!0),s=this.compileAndRun(i,[n]),u=new em(a),c=this.compileAndRun(u,[e,s],n.dtype);return s.dispose(),c},t.prototype.avgPoolBackprop=function(e,n,o){var a=new mv(o);return this.compileAndRun(a,[e],n.dtype)},t.prototype.cast=function(e,n){return Ni(e,n,this)},t.prototype.unstack=function(e,n){for(var o=e.shape[n],a=new Array(e.rank-1),i=0,s=0;s1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+n}));var a=e.shape[0],i=o==="NHWC"?e.shape[1]:e.shape[2],s=o==="NHWC"?e.shape[2]:e.shape[3],u=o==="NHWC"?e.shape[3]:e.shape[1],c=i*n,l=s*n,h=u/(n*n),f=new Lv(o==="NHWC"?[a,c,l,h]:[a,h,c,l],n,o);return this.compileAndRun(f,[e])},t.prototype.split=function(e,n,o){return vl(e,n,o)},t.prototype.scatterND=function(e,n,o){var a=Sr(0,e,o),i=a.sliceRank,s=a.numUpdates,u=a.sliceSize,c=a.strides,l=a.outputSize,h=[l/u,u],f=e.reshape([s,i]),d=n.reshape([s,u]);if(l===0)return Io(Ge([]),o);var p=q(0),m=new du(s,i,f.rank,d.rank,c,h);return this.compileAndRun(m,[d,f,p]).reshape(o)},t.prototype.sparseToDense=function(e,n,o,a){var i=Sr(0,e,o),s=i.sliceRank,u=i.numUpdates,c=i.strides,l=i.outputSize,h=new du(u,s,e.rank,n.rank,c,[l,1]);return this.compileAndRun(h,[n,e,a]).reshape(o)},t.prototype.fft=function(e){return this.fftImpl(e,!1)},t.prototype.ifft=function(e){return this.fftImpl(e,!0)},t.prototype.fftImpl=function(e,n){var o=this.texData.get(e.dataId),a=new hu(Hv,e.shape,n),i=new hu(qv,e.shape,n),s=[this.makeComplexComponentTensorInfo(e,o.complexTensors.real),this.makeComplexComponentTensorInfo(e,o.complexTensors.imag)],u=this.compileAndRun(a,s),c=this.compileAndRun(i,s),l=this.complex(u,c).as2D(e.shape[0],e.shape[1]);return u.dispose(),c.dispose(),l},t.prototype.gatherND=function(e,n){var o=n.shape,a=o[o.length-1],i=Ri(e,n),s=i[0],u=i[1],c=i[2],l=i[3],h=n.reshape([u,a]),f=e.reshape([e.size/c,c]),d=new Xv(a,l,[u,c]);return this.compileAndRun(d,[f,h]).reshape(s)},t.prototype.fill=function(e,n,o){if((o=o||or(n))==="string"){var a=wr(o,Z(e));return a.fill(n),A.makeTensor(a,e,o,this)}var i=new jv(e,n),s=i.getCustomSetupFunc(n);return this.compileAndRun(i,[],o,s)},t.prototype.onesLike=function(e){if(e.dtype==="string")throw new Error("onesLike is not supported under string dtype");return this.fill(e.shape,1,e.dtype)},t.prototype.zerosLike=function(e){return this.fill(e.shape,e.dtype==="string"?"":0,e.dtype)},t.prototype.linspace=function(e,n,o){return Pi(e,n,o)},t.prototype.makeTensorInfo=function(e,n){var o=this.write(null,e,n);return this.texData.get(o).usage=null,{dataId:o,shape:e,dtype:n}},t.prototype.makeOutput=function(e,n){var o=this.makeTensorInfo(e,n).dataId;return A.makeTensorFromDataId(o,e,n,this)},t.prototype.unpackTensor=function(e){var n=new Om(e.shape);return this.runWebGLProgram(n,[e],e.dtype)},t.prototype.packTensor=function(e){var n=new om(e.shape);return this.runWebGLProgram(n,[e],e.dtype,null,!0)},t.prototype.packedReshape=function(e,n){var o=[Er(e.shape)].concat(Ir(e.shape)),a={dtype:e.dtype,shape:o,dataId:e.dataId},i=[Er(n)].concat(Ir(n)),s=new um(i,o),u=this.runWebGLProgram(s,[a],e.dtype,null,!0);return{dataId:u.dataId,shape:n,dtype:u.dtype}},t.prototype.decode=function(e){var n,o=this.texData.get(e),a=o.isPacked,i=o.shape,s=o.dtype,u=fo(i);return n=a?new Bv(u):new Ov(u),{dtype:s,shape:i,dataId:this.runWebGLProgram(n,[{shape:u,dtype:s,dataId:e}],s,null,!0).dataId}},t.prototype.runWebGLProgram=function(e,n,o,a,i){var s=this;i===void 0&&(i=!1);var u=this.makeTensorInfo(e.outputShape,o),c=this.texData.get(u.dataId);if(e.packedOutput&&(c.isPacked=!0),e.outPackingScheme===_r.DENSE){var l=gr(e.outputShape);c.texShape=l.map((function(b){return 2*b}))}if(e.outTexUsage!=null&&(c.usage=e.outTexUsage),Z(u.shape)===0)return c.values=Qn(u.dtype,0),u;var h=[],f=n.map((function(b){if(b.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var y=s.texData.get(b.dataId);if(y.texture==null){if(!e.packedInputs&&Z(b.shape)<=M().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:b.shape,texData:null,isUniform:!0,uniformValues:y.values};e.packedInputs&&(y.isPacked=!0,y.shape=b.shape)}else if(!!y.isPacked!=!!e.packedInputs)b=y.isPacked?s.unpackTensor(b):s.packTensor(b),h.push(b),y=s.texData.get(b.dataId);else if(y.isPacked&&!mr(y.shape,b.shape)){var w=b,_=b.shape;b.shape=y.shape,b=s.packedReshape(b,_),h.push(b),y=s.texData.get(b.dataId),w.shape=_}return s.uploadToGPU(b.dataId),{shape:b.shape,texData:y,isUniform:!1}}));this.uploadToGPU(u.dataId);var d,p={shape:u.shape,texData:c,isUniform:!1},m=(function(b,y,w){var _="";y.concat(w).forEach((function(I){var R=I.texData!=null&&I.texData.slice!=null&&I.texData.slice.flatOffset>0,F=I.isUniform?"uniform":I.texData.texShape;_+=I.shape+"_"+F+"_"+R}));var S=b.userCode,k=b.constructor.name;return k+="_"+_+"_"+S})(e,f,p),v=this.getAndSaveBinary(m,(function(){return(function(b,y,w,_){var S=y.userCode,k=w.map((function(W,G){var H={logicalShape:W.shape,texShape:W.isUniform?null:W.texData.texShape,isUniform:W.isUniform,isPacked:!W.isUniform&&W.texData.isPacked,flatOffset:null};return W.texData!=null&&W.texData.slice!=null&&W.texData.slice.flatOffset>0&&(H.flatOffset=W.texData.slice.flatOffset),{name:y.variableNames[G],shapeInfo:H}})),I=k.map((function(W){return W.shapeInfo})),R={logicalShape:_.shape,texShape:_.texData.texShape,isUniform:!1,isPacked:_.texData.isPacked,flatOffset:null},F=lv(k,R,S,y.packedInputs),T=b.createProgram(F),L=null,O=b.getUniformLocation(T,"NAN",!1);M().getNumber("WEBGL_VERSION")===1&&(L=b.getUniformLocation(T,"INFINITY",!1));for(var B={},U=0;U0)return 32}return 16}))),this.floatPrecisionValue},t.prototype.epsilon=function(){return this.floatPrecision()===32?1e-7:1e-4},t.prototype.uploadToGPU=function(e){var n,o=this.texData.get(e),a=o.shape,i=o.dtype,s=o.values,u=o.texture,c=o.usage,l=o.isPacked;if(u==null){var h,f=this.activeTimers!=null;f&&(h=gt());var d=o.texShape;if(d==null&&(d=Ic(a,l),o.texShape=d),s!=null){var p=fo(a),m=void 0,v=d[1],g=d[0],x=s instanceof Uint8Array;l?(v=(n=Lr(d[0],d[1]))[0],g=n[1],m=new Gv(p,[g,v],x)):m=new Vv(p,[g,v],x);var b=this.makeTensorInfo([g,v],i);this.texData.get(b.dataId).usage=x?ct.PIXELS:ct.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(b.dataId),v,g,s);var y=this.runWebGLProgram(m,[b],i,null,!0),w=this.texData.get(y.dataId);o.texture=w.texture,o.texShape=w.texShape,o.isPacked=w.isPacked,o.usage=w.usage,this.disposeData(b.dataId),this.texData.delete(y.dataId),o.values=null,f&&(this.uploadWaitMs+=gt()-h)}else{var _=this.acquireTexture(d,c,i,l);o.texture=_}}},t.prototype.convertAndCacheOnCPU=function(e,n){var o=this.texData.get(e),a=o.dtype;return this.releaseGPUData(e),n!=null&&(o.values=(function(i,s){if(s==="float32"||s==="complex64")return i;if(s==="int32"||s==="bool"){for(var u=s==="int32"?new Int32Array(i.length):new Uint8Array(i.length),c=0;c1024*this.numMBBeforeWarning*1024){var 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,n,a)},t.prototype.computeBytes=function(e,n){return e[0]*e[1]*hi(n)},t})(Ti);ic()&&A.registerBackend("webgl",(function(){return new jl}),2);var Kl=D({square_:function(r){var t=C(r,"x","square"),e=[t];return A.runKernelFunc((function(n,o){return o([t]),n.square(t)}),{x:t},null,"Square",{},e,[])}}),Tr="SquaredDifference",Ui=D({squaredDifference_:function(r,t){var e,n=C(r,"a","squaredDifference"),o=C(t,"b","squaredDifference");e=Ie(n,o),n=e[0],o=e[1],ce(n.shape,o.shape);var a={a:n,b:o},i=[n,o];return A.runKernelFunc((function(s,u){var c=s.squaredDifference(n,o);return u([n,o]),c}),a,(function(s,u){var c=u[0],l=u[1],h=q(2);return{a:function(){return s.mul(c.sub(l).mul(h))},b:function(){return s.mul(l.sub(c).mul(h))}}}),Tr,{},i,[])}}),Xl=D({abs_:function(r){var t=C(r,"x","abs");return t.dtype==="complex64"?A.runKernelFunc((function(e){return e.complexAbs(t)}),{$x:t}):A.runKernelFunc((function(e,n){var o=e.abs(t);return n([t]),o}),{x:t},(function(e,n){var o=n[0];return{x:function(){return e.mul(o.toFloat().step(-1))}}}),"Abs")}}),Yl=D({acos_:function(r){var t=C(r,"x","acos");return A.runKernelFunc((function(e,n){var o=e.acos(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return e.divStrict(q(1).sub(o.toFloat().square()).sqrt()).neg()}}}))}}),$l=D({acosh_:function(r){var t=C(r,"x","acosh");return A.runKernelFunc((function(e,n){var o=e.acosh(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return e.divStrict(o.toFloat().square().sub(1).sqrt())}}}))}}),Jl=D({asin_:function(r){var t=C(r,"x","asin");return A.runKernelFunc((function(e,n){var o=e.asin(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return e.divStrict(q(1).sub(o.toFloat().square()).sqrt())}}}))}}),Ql=D({asinh_:function(r){var t=C(r,"x","asinh");return A.runKernelFunc((function(e,n){var o=e.asinh(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return e.divStrict(q(1).add(o.toFloat().square()).sqrt())}}}))}}),Zl=D({atan_:function(r){var t=C(r,"x","atan");return A.runKernelFunc((function(e,n){var o=e.atan(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return e.div(o.toFloat().square().add(1))}}}))}}),eh=D({atanh_:function(r){var t=C(r,"x","atanh");return A.runKernelFunc((function(e,n){var o=e.atanh(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return e.div(q(1).sub(o.toFloat().square()))}}}))}}),th=D({ceil_:function(r){var t=C(r,"x","ceil");return A.runKernelFunc((function(e){return e.ceil(t)}),{$x:t},(function(e){return{$x:function(){return de(e)}}}))}}),Wo=D({clipByValue_:function(r,t,e){var n=C(r,"x","clipByValue");E(t<=e,(function(){return"Error in clip: min ("+t+") must be less than or equal to max ("+e+")."}));var o=[n],a={min:t,max:e};return A.runKernelFunc((function(i,s){var u=i.clip(n,t,e);return s([n]),u}),{x:n},(function(i,s){var u=s[0];return{x:function(){return i.where(u.greaterEqual(t).logicalAnd(u.lessEqual(e)),de(i))}}}),"ClipByValue",a,o)}}),nh=D({cos_:function(r){var t=C(r,"x","cos"),e=[t];return A.runKernelFunc((function(n,o){var a=n.cos(t);return o([t]),a}),{x:t},(function(n,o){var a=o[0];return{x:function(){return a.toFloat().sin().neg().mul(n)}}}),"Cos",{},e)}}),rh=D({cosh_:function(r){var t=C(r,"x","cosh");return A.runKernelFunc((function(e,n){var o=e.cosh(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return o.toFloat().sinh().mulStrict(e)}}}))}}),oh=D({erf_:function(r){var t=C(r,"x","erf");return E(t.dtype==="int32"||t.dtype==="float32",(function(){return"Input dtype must be `int32` or `float32`."})),t.dtype==="int32"&&(t=t.toFloat()),A.runKernelFunc((function(e,n){var o=e.erf(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return e.mul(o.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}}))}}),Ro=D({exp_:function(r){var t=C(r,"x","exp");return A.runKernelFunc((function(e,n){var o=e.exp(t);return n([o]),o}),{x:t},(function(e,n){return{x:function(){return e.mulStrict(n[0])}}}),"Exp",{},[],[!0])}}),ah=D({expm1_:function(r){var t=C(r,"x","expm1");return A.runKernelFunc((function(e,n){var o=e.expm1(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return e.mul(o.exp())}}}))}}),ih=D({floor_:function(r){var t=C(r,"x","floor");return A.runKernelFunc((function(e){return e.floor(t)}),{$x:t},(function(e){return{$x:function(){return de(e)}}}))}}),sh=D({log_:function(r){var t=C(r,"x","log"),e=[t];return A.runKernelFunc((function(n,o){var a=n.log(t);return o([t]),a}),{x:t},(function(n,o){var a=o[0];return{x:function(){return n.div(a.toFloat())}}}),"Log",{},e)}}),uh=D({log1p_:function(r){var t=C(r,"x","log1p");return A.runKernelFunc((function(e,n){var o=e.log1p(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return e.div(o.add(1))}}}))}}),ch=D({logSigmoid_:function(r){var t=C(r,"x","logSigmoid");return A.runKernelFunc((function(e,n){var o=e.softplus(t.neg()).neg();return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return e.mul(o.neg().sigmoid())}}}))}}),Fr=D({neg_:function(r){var t=C(r,"x","neg"),e=[t];return A.runKernelFunc((function(n){return n.neg(t)}),{x:t},(function(n){return{x:function(){return n.neg()}}}),"Neg",{},e)}}),lh=D({reciprocal_:function(r){var t=C(r,"x","reciprocal");return A.runKernelFunc((function(e,n){var o=e.reciprocal(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return e.div(o.square().neg())}}}))}}),hh=D({round_:function(r){var t=C(r,"x","round");return A.runKernelFunc((function(e){return e.round(t)}),{$x:t},(function(e){return{$x:function(){return de(e)}}}))}}),Vi=D({rsqrt_:function(r){var t=C(r,"x","rsqrt"),e=[t];return A.runKernelFunc((function(n,o){var a=n.rsqrt(t);return o([t]),a}),{x:t},(function(n,o){var a=o[0];return{x:function(){return n.div(a.pow(1.5).mul(2)).neg()}}}),"Rsqrt",{},e)}}),Gi=D({sigmoid_:function(r){var t=C(r,"x","sigmoid");return A.runKernelFunc((function(e,n){var o=e.sigmoid(t);return n([o]),o}),{x:t},(function(e,n){var o=n[0];return{x:function(){return e.mul(o.mul(q(1).sub(o)))}}}),"Sigmoid")}}),fh=D({sign_:function(r){var t=C(r,"x","sign");return A.runKernelFunc((function(e){return e.sign(t)}),{$x:t},(function(e){return{$x:function(){return de(e)}}}))}}),dh=D({isNaN_:function(r){var t=C(r,"x","isNaN");return A.runKernelFunc((function(e){return e.isNaN(t)}),{$x:t},(function(e){return{$x:function(){return de(e)}}}))}}),ph=D({isInf_:function(r){var t=C(r,"x","isInf");return A.runKernelFunc((function(e){return e.isInf(t)}),{$x:t},(function(e){return{$x:function(){return de(e)}}}))}}),vh=D({isFinite_:function(r){var t=C(r,"x","isFinite");return A.runKernelFunc((function(e){return e.isFinite(t)}),{$x:t},(function(e){return{$x:function(){return de(e)}}}))}}),mh=D({sin_:function(r){var t=C(r,"x","sin"),e=[t];return A.runKernelFunc((function(n,o){var a=n.sin(t);return o([t]),a}),{x:t},(function(n,o){var a=o[0];return{x:function(){return a.toFloat().cos().mul(n)}}}),"Sin",{},e)}}),gh=D({sinh_:function(r){var t=C(r,"x","sinh");return A.runKernelFunc((function(e,n){var o=e.sinh(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return o.toFloat().cosh().mulStrict(e)}}}))}}),yh=D({softplus_:function(r){var t=C(r,"x","softplus");return A.runKernelFunc((function(e,n){var o=e.softplus(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return e.mul(o.sigmoid())}}}))}}),xh=D({sqrt_:function(r){var t=C(r,"x","sqrt");return A.runKernelFunc((function(e,n){var o=e.sqrt(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return e.div(o.toFloat().sqrt().mul(2))}}}))}}),bh=D({step_:function(r,t){t===void 0&&(t=0);var e=C(r,"x","step");return A.runKernelFunc((function(n){return n.step(e,t)}),{$x:e},(function(n){return{$x:function(){return de(n)}}}))}}),wh=D({tan_:function(r){var t=C(r,"x","tan");return A.runKernelFunc((function(e,n){var o=e.tan(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){return e.div(o.cos().square())}}}))}}),Ch=D({tanh_:function(r){var t=C(r,"x","tanh");return A.runKernelFunc((function(e,n){var o=e.tanh(t);return n([o]),o}),{x:t},(function(e,n){var o=n[0];return{x:function(){return q(1).sub(o.square()).mulStrict(e)}}}),"Tanh",{},null,[!0])}});function _h(r,t,e,n,o,a){var i,s,u=C(r,"x","batchNorm"),c=C(t,"mean","batchNorm"),l=C(e,"variance","batchNorm");return o!=null&&(i=C(o,"scale","batchNorm")),n!=null&&(s=C(n,"offset","batchNorm")),E(u.rank===2,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),E(c.rank===2||c.rank===1,(function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+c.rank+"."})),E(l.rank===2||l.rank===1,(function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+l.rank+"."})),i!=null&&E(i.rank===2||i.rank===1,(function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+i.rank+"."})),s!=null&&E(s.rank===2||s.rank===1,(function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."})),Ur(u,c,l,s,i,a)}function Eh(r,t,e,n,o,a){var i,s,u=C(r,"x","batchNorm"),c=C(t,"mean","batchNorm"),l=C(e,"variance","batchNorm");return o!=null&&(i=C(o,"scale","batchNorm")),n!=null&&(s=C(n,"offset","batchNorm")),E(u.rank===3,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),E(c.rank===3||c.rank===1,(function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+c.rank+"."})),E(l.rank===3||l.rank===1,(function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+l.rank+"."})),i!=null&&E(i.rank===3||i.rank===1,(function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+i.rank+"."})),s!=null&&E(s.rank===3||s.rank===1,(function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."})),Ur(u,c,l,s,i,a)}function Ih(r,t,e,n,o,a){var i,s,u=C(r,"x","batchNorm"),c=C(t,"mean","batchNorm"),l=C(e,"variance","batchNorm");return o!=null&&(i=C(o,"scale","batchNorm")),n!=null&&(s=C(n,"offset","batchNorm")),E(u.rank===4,(function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."})),E(c.rank===4||c.rank===1,(function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+c.rank+"."})),E(l.rank===4||l.rank===1,(function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+l.rank+"."})),i!=null&&E(i.rank===4||i.rank===1,(function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+i.rank+"."})),s!=null&&E(s.rank===4||s.rank===1,(function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."})),Ur(u,c,l,s,i,a)}function Ur(r,t,e,n,o,a){a==null&&(a=.001);var i,s,u,c=C(r,"x","batchNorm"),l=C(t,"mean","batchNorm"),h=C(e,"variance","batchNorm");o!=null&&(i=C(o,"scale","batchNorm")),n!=null&&(s=C(n,"offset","batchNorm")),E(l.rank===h.rank,(function(){return"Batch normalization gradient requires mean and variance to have equal ranks."})),E(s==null||l.rank===s.rank,(function(){return"Batch normalization gradient requires mean and offset to have equal ranks."})),E(i==null||l.rank===i.rank,(function(){return"Batch normalization gradient requires mean and scale to have equal ranks."})),u=c.rank===0||c.rank===1?c.as4D(1,1,1,c.size):c.rank===2?c.as4D(1,1,c.shape[0],c.shape[1]):c.rank===3?c.as4D(1,c.shape[0],c.shape[1],c.shape[2]):c;var f=[c,l,h,i];return A.runKernelFunc((function(d,p){var m=d.batchNormalization(u,to(l),to(h),a,to(i),to(s));return p([c,l,h,i]),m}),{x:c,mean:l,variance:h,scale:i,offset:s},(function(d,p){var m=p,v=m[0],g=m[1],x=m[2],b=m[3],y=b??q(1),w=Oe(g.shape,u.shape),_=[];if(g.rank===1){for(var S=0;S0&&(s=s.sum(u)),s.reshape(n.shape)},b:function(){var s=i,u=Oe(o.shape,a);return u.length>0&&(s=s.sum(u)),s.reshape(o.shape)}}}),"Add")}}),Mh=D({addN_:function(r){E(Array.isArray(r),(function(){return"The argument passed to tf.addN() must be a list of tensors"})),E(r.length>=1,(function(){return"Must pass at least one tensor to tf.addN(), but got "+r.length}));var t=r.map((function(o,a){return C(o,"tensors"+a,"addN")})),e=t[0];t.forEach((function(o){if(o.dtype!==e.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")})),t.forEach((function(o){if(!Ne(o.shape,e.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));var n=t;return A.runKernelFunc((function(o){return o.addN(t)}),n,(function(o){var a={};return t.forEach((function(i,s){a[s]=function(){return o.clone()}})),a}),"AddN")}}),Oh=D({addStrict_:function(r,t){var e=C(r,"a","addStrict"),n=C(t,"b","addStrict");return me(e.shape,n.shape,"Error in addStrict: "),e.add(n)}}),Bh=D({atan2_:function(r,t){var e,n=C(r,"a","atan2"),o=C(t,"b","atan2");e=Ie(n,o),n=e[0],o=e[1];var a=ce(n.shape,o.shape);return A.runKernelFunc((function(i,s){var u=i.atan2(n,o);return s([n,o]),u}),{$a:n,$b:o},(function(i,s){var u=s[0],c=s[1];return{$a:function(){var l=ue(u.square(),c.square()),h=i.mul(c.div(l)),f=Oe(u.shape,a);return f.length>0&&(h=h.sum(f)),h.reshape(u.shape)},$b:function(){var l=ue(u.square(),c.square()),h=Fr(i.mul(u.div(l))),f=Oe(c.shape,a);return f.length>0&&(h=h.sum(f)),h.reshape(c.shape)}}}))}}),vt=D({div_:function(r,t){var e,n=C(r,"a","div"),o=C(t,"b","div");if(e=Ie(n,o),n=e[0],o=e[1],n.dtype==="int32"&&o.dtype==="int32")return Ki(n,o);var a=ce(n.shape,o.shape);return A.runKernelFunc((function(i,s){var u=i.realDivide(n,o);return s([n,o]),u}),{a:n,b:o},(function(i,s){var u=s[0],c=s[1];return{a:function(){var l=i.div(c.toFloat()),h=Oe(u.shape,a);return h.length>0?l.sum(h).reshape(u.shape):l},b:function(){var l=i.mul(u.toFloat()),h=Oe(c.shape,a);h.length>0&&(l=l.sum(h).reshape(c.shape));var f=c.square();return l.div(f.toFloat()).neg()}}}),"Div")}}),Lh=D({divNoNan_:function(r,t){var e,n=C(r,"a","div"),o=C(t,"b","div");n=(e=Ie(n,o))[0],o=e[1];var a=vt(n,o),i=de(a),s=o.equal(i);return dn(s,i,a)}}),Wh=D({divStrict_:function(r,t){var e=C(r,"a","div"),n=C(t,"b","div");return me(e.shape,n.shape,"Error in divideStrict: "),e.div(n)}}),Ki=D({floorDiv_:function(r,t){var e,n=C(r,"a","floorDiv"),o=C(t,"b","floorDiv");e=Ie(n,o),n=e[0],o=e[1];var a=ce(n.shape,o.shape);return A.runKernelFunc((function(i,s){var u=i.floorDiv(n,o);return s([n,o]),u}),{a:n,b:o},(function(i,s){var u=s[0],c=s[1];return{a:function(){var l=i.div(c.toFloat()),h=Oe(u.shape,a);return h.length>0?l.sum(h).reshape(u.shape):l},b:function(){var l=i.mul(u.toFloat()),h=Oe(c.shape,a);h.length>0&&(l=l.sum(h).reshape(c.shape));var f=c.square();return l.div(f.toFloat()).neg()}}}),"FloorDiv")}}),Uo=D({maximum_:function(r,t){var e,n=C(r,"a","maximum"),o=C(t,"b","maximum");return e=Ie(n,o),n=e[0],o=e[1],n.dtype==="bool"&&(n=n.toInt(),o=o.toInt()),ce(n.shape,o.shape),A.runKernelFunc((function(a,i){var s=a.maximum(n,o);return i([n,o]),s}),{a:n,b:o},(function(a,i){var s=i[0],u=i[1];return{a:function(){return a.mul(s.greaterEqual(u).toFloat())},b:function(){return a.mul(s.less(u).toFloat())}}}),"Maximum")}}),zh=D({maximumStrict_:function(r,t){var e=C(r,"a","maximumStrict"),n=C(t,"b","maximumStrict");return me(e.shape,n.shape,"Error in maximumStrict: "),e.maximum(n)}}),Xi=D({minimum_:function(r,t){var e,n=C(r,"a","minimum"),o=C(t,"b","minimum");return e=Ie(n,o),n=e[0],o=e[1],n.dtype==="bool"&&(n=n.toInt(),o=o.toInt()),ce(n.shape,o.shape),A.runKernelFunc((function(a,i){var s=a.minimum(n,o);return i([n,o]),s}),{a:n,b:o},(function(a,i){var s=i[0],u=i[1];return{a:function(){return a.mul(s.lessEqual(u).toFloat())},b:function(){return a.mul(s.greater(u).toFloat())}}}),"Minimum")}}),Uh=D({minimumStrict_:function(r,t){var e=C(r,"a","minimumStrict"),n=C(t,"b","minimumStrict");return me(e.shape,n.shape,"Error in minimumStrict: "),e.minimum(n)}}),Vh=D({mod_:function(r,t){var e,n=C(r,"a","mod"),o=C(t,"b","mod");e=Ie(n,o),n=e[0],o=e[1];var a=ce(n.shape,o.shape);return A.runKernelFunc((function(i,s){var u=i.mod(n,o);return s([n,o]),u}),{$a:n,$b:o},(function(i,s){var u=s[0],c=s[1];return{$a:function(){var l=Oe(u.shape,a);return l.length>0?i.sum(l).reshape(u.shape):i},$b:function(){var l=i.mul(u.div(c).floor().neg()),h=Oe(c.shape,a);return h.length>0?l.sum(h).reshape(c.shape):l}}}))}}),Gh=D({modStrict_:function(r,t){var e=C(r,"a","modStrict"),n=C(t,"b","modStrict");return me(e.shape,n.shape,"Error in modStrict: "),e.mod(n)}}),Xe=D({mul_:function(r,t){var e,n=C(r,"a","mul"),o=C(t,"b","mul");e=Ie(n,o),n=e[0],o=e[1];var a=ce(n.shape,o.shape);return A.runKernelFunc((function(i,s){var u=i.multiply(n,o);return s([n,o]),u}),{a:n,b:o},(function(i,s){var u=s[0],c=s[1];return{a:function(){var l=i.mul(c.toFloat()),h=Oe(u.shape,a);return h.length>0?l.sum(h).reshape(u.shape):l},b:function(){var l=i.mul(u.toFloat()),h=Oe(c.shape,a);return h.length>0?l.sum(h).reshape(c.shape):l}}}),"Mul")}}),Hh=D({mulStrict_:function(r,t){var e=C(r,"a","mul"),n=C(t,"b","mul");return me(e.shape,n.shape,"Error in multiplyStrict: "),e.mul(n)}}),Nr=D({pow_:function(r,t){var e,n=C(r,"base","pow"),o=C(t,"exp","pow");e=Ie(n,o),n=e[0],o=e[1];var a=ce(n.shape,o.shape),i=[n,o];return A.runKernelFunc((function(s,u){var c=s.pow(n,o);return u([n,o,c]),c}),{a:n,b:o},(function(s,u){var c=u[0],l=u[1],h=u[2];return{a:function(){var f=l.toFloat(),d=s.mul(f.mul(c.pow(f.sub(q(1))))),p=Oe(c.shape,a);return p.length>0&&(d=d.sum(p)),d.reshape(c.shape)},b:function(){var f=c.greater(0),d=c.log().where(f,de(c)),p=s.mul(h.mul(d)),m=Oe(l.shape,a);return m.length>0&&(p=p.sum(m)),p.reshape(l.shape)}}}),"Pow",{},i,[!0])}}),qh=D({powStrict_:function(r,t){return me(r.shape,t.shape,"Error in powStrict: "),r.pow(t)}}),jh=D({squaredDifferenceStrict_:function(r,t){var e=C(r,"a","squaredDifferenceStrict"),n=C(t,"b","squaredDifferenceStrict");return me(e.shape,n.shape,"Error in squaredDifferenceStrict: "),e.squaredDifference(n)}}),Be=D({sub_:function(r,t){var e,n=C(r,"a","sub"),o=C(t,"b","sub");e=Ie(n,o),n=e[0],o=e[1];var a=ce(n.shape,o.shape);return A.runKernelFunc((function(i){return i.subtract(n,o)}),{a:n,b:o},(function(i){return{a:function(){var s=i,u=Oe(n.shape,a);return u.length>0&&(s=s.sum(u)),s.reshape(n.shape)},b:function(){var s=i,u=Oe(o.shape,a);return u.length>0&&(s=s.sum(u)),s.neg().reshape(o.shape)}}}),"Sub")}}),Kh=D({subStrict_:function(r,t){var e=C(r,"a","subStrict"),n=C(t,"b","subStrict");return me(e.shape,n.shape,"Error in subStrict: "),e.sub(n)}}),Yi=D({equal_:function(r,t){var e,n=C(r,"a","equal"),o=C(t,"b","equal");return e=Ie(n,o),n=e[0],o=e[1],ce(n.shape,o.shape),A.runKernelFunc((function(a){return a.equal(n,o)}),{$a:n,$b:o})}}),Xh=D({equalStrict_:function(r,t){var e=C(r,"a","equalStrict"),n=C(t,"b","equalStrict");return me(e.shape,n.shape,"Error in equalStrict: "),e.equal(n)}}),Yh=D({greater_:function(r,t){var e,n=C(r,"a","greater"),o=C(t,"b","greater");return e=Ie(n,o),n=e[0],o=e[1],ce(n.shape,o.shape),A.runKernelFunc((function(a){return a.greater(n,o)}),{a:n,b:o},null,"Greater")}}),$i=D({greaterEqual_:function(r,t){var e,n=C(r,"a","greaterEqual"),o=C(t,"b","greaterEqual");return e=Ie(n,o),n=e[0],o=e[1],ce(n.shape,o.shape),A.runKernelFunc((function(a,i){var s=a.greaterEqual(n,o);return i([n,o]),s}),{a:n,b:o},(function(a,i){var s=i[0],u=i[1];return{a:function(){return de(s)},b:function(){return de(u)}}}),"GreaterEqual")}}),$h=D({greaterEqualStrict_:function(r,t){var e=C(r,"a","greaterEqualStrict"),n=C(t,"b","greaterEqualStrict");return me(e.shape,n.shape,"Error in greaterEqualStrict: "),e.greaterEqual(n)}}),Jh=D({greaterStrict_:function(r,t){var e=C(r,"a","greaterStrict"),n=C(t,"b","greaterStrict");return me(e.shape,n.shape,"Error in greaterStrict: "),e.greater(n)}}),Qh=D({less_:function(r,t){var e,n=C(r,"a","less"),o=C(t,"b","less");return e=Ie(n,o),n=e[0],o=e[1],ce(n.shape,o.shape),A.runKernelFunc((function(a){return a.less(n,o)}),{a:n,b:o},null,"Less")}}),Zh=D({lessEqual_:function(r,t){var e,n=C(r,"a","lessEqual"),o=C(t,"b","lessEqual");return e=Ie(n,o),n=e[0],o=e[1],ce(n.shape,o.shape),A.runKernelFunc((function(a,i){var s=a.lessEqual(n,o);return i([n,o]),s}),{a:n,b:o},null,"LessEqual")}}),ef=D({lessEqualStrict_:function(r,t){var e=C(r,"a","lessEqualStrict"),n=C(t,"b","lessEqualStrict");return me(e.shape,n.shape,"Error in lessEqualStrict: "),e.lessEqual(n)}}),tf=D({lessStrict_:function(r,t){var e=C(r,"a","lessStrict"),n=C(t,"b","lessStrict");return me(e.shape,n.shape,"Error in lessStrict: "),e.less(n)}}),nf=D({notEqual_:function(r,t){var e,n=C(r,"a","notEqual"),o=C(t,"b","notEqual");return e=Ie(n,o),n=e[0],o=e[1],ce(n.shape,o.shape),A.runKernelFunc((function(a){return a.notEqual(n,o)}),{a:n,b:o},null,"NotEqual")}}),rf=D({notEqualStrict_:function(r,t){var e=C(r,"a","notEqualStrict"),n=C(t,"b","notEqualStrict");return me(e.shape,n.shape,"Error in notEqualStrict: "),e.notEqual(n)}});function Cu(r,t){for(var e=[],n=r;n0,(function(){return"mask cannot be scalar"})),me(s.slice(a,a+i),o.shape,"mask's shape must match the first K dimensions of tensor's shape,"),u=1,c=a;c=2&&i.rank>=2&&a.rank===i.rank,(function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+"."})),E(Ne(h,f),(function(){return"Error in matMul: outer dimensions ("+h+") and ("+f+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."})),E(s===u,(function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+e+" and transposeB="+n+" must match."}));var m=a.shape.slice(0,-2).concat([c,l]),v=e?a.as3D(d,s,c):a.as3D(d,c,s),g=n?i.as3D(p,l,u):i.as3D(p,u,l),x={transposeA:e,transposeB:n};return A.runKernelFunc((function(b,y){var w=b.batchMatMul(v,g,e,n);return y([v,g]),w}),{a:v,b:g},(function(b,y){var w=y,_=w[0],S=w[1];return e||n?!e&&n?{a:function(){return b.matMul(S,!1,!1)},b:function(){return b.matMul(_,!0,!1)}}:e&&!n?{a:function(){return S.matMul(b,!1,!0)},b:function(){return _.matMul(b,!1,!1)}}:{a:function(){return S.matMul(b,!0,!0)},b:function(){return b.matMul(_,!0,!0)}}:{a:function(){return b.matMul(S,!1,!0)},b:function(){return _.matMul(b,!0,!1)}}}),"BatchMatMul",x).reshape(m)}}),vf=D({dot_:function(r,t){var e=C(r,"t1","dot"),n=C(t,"t2","dot");E(!(e.rank!==1&&e.rank!==2||n.rank!==1&&n.rank!==2),(function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+e.rank+" and "+n.rank+"."}));var o=e.rank===1?e.size:e.shape[1],a=n.rank===1?n.size:n.shape[0];return E(o===a,(function(){return"Error in dot: inner dimensions of inputs must match, but got "+o+" and "+a+"."})),e.rank===1&&n.rank===1?e.as2D(1,-1).matMul(n.as2D(-1,1)).asScalar():e.rank===1&&n.rank===2?e.as2D(1,-1).matMul(n.as2D(n.shape[0],n.shape[1])).as1D():e.rank===2&&n.rank===1?e.matMul(n.as2D(-1,1)).as1D():e.matMul(n.as2D(n.shape[0],n.shape[1]))}}),mf=D({outerProduct_:function(r,t){var e=C(r,"v1","outerProduct"),n=C(t,"v2","outerProduct");return E(e.rank===1&&n.rank===1,(function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+e.rank+" and "+n.rank+"."})),e.as2D(-1,1).matMul(n.as2D(1,-1))}}),ir=D({reverse_:function(r,t){var e=C(r,"x","reverse");if(e.rank===0)return e.clone();var n=Le(t,e.shape);return A.runKernelFunc((function(o){return o.reverse(e,n)}),{$x:e},(function(o){return{$x:function(){return o.reverse(n)}}})).reshapeAs(e)}}),gf=D({reverse1d_:function(r){var t=C(r,"x","reverse");return E(t.rank===1,(function(){return"Error in reverse1D: x must be rank 1 but got rank "+t.rank+"."})),ir(t,0)}}),yf=D({reverse2d_:function(r,t){var e=C(r,"x","reverse");return E(e.rank===2,(function(){return"Error in reverse2D: x must be rank 2 but got rank "+e.rank+"."})),ir(e,t)}}),xf=D({reverse3d_:function(r,t){var e=C(r,"x","reverse");return E(e.rank===3,(function(){return"Error in reverse3D: x must be rank 3 but got rank "+e.rank+"."})),ir(e,t)}}),bf=D({reverse4d_:function(r,t){var e=C(r,"x","reverse");return E(e.rank===4,(function(){return"Error in reverse4D: x must be rank 4 but got rank "+e.rank+"."})),ir(e,t)}});function wf(r,t,e,n,o,a){var i=C(r,"x","maxPool"),s=i,u=!1;i.rank===3&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),E(s.rank===4,(function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."})),E(tt(e,n),(function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+n+"'"})),a!=null&&E(De(o),(function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."}));var c=er(s.shape,t,e,n,o,a);if(c.filterWidth===1&&c.filterHeight===1&&Ne(c.inShape,c.outShape))return i.clone();var l=[s],h=A.runKernelFunc((function(f,d){var p=f.maxPool(s,c);return d([s,p]),p}),{x:s},(function(f,d){var p=d[0],m=d[1];return{x:function(){return(function(v,g,x,b,y,w,_,S){var k=C(v,"dy","maxPoolBackprop"),I=C(g,"input","maxPoolBackprop"),R=C(x,"output","maxPoolBackprop");E(I.rank===k.rank,(function(){return"Rank of input ("+I.rank+") does not match rank of dy ("+k.rank+")"})),E(tt(y,w),(function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+y+" and dilations '"+w+"'"})),E(k.rank===4,(function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+k.rank+"."})),E(I.rank===4,(function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+I.rank+"."}));var F=er(I.shape,b,y,w,_,S);return A.runKernelFunc((function(T){return T.maxPoolBackprop(k,I,R,F)}),{$dy:k,$input:I})})(f,p,m,t,e,n,o)}}}),"MaxPool",c,l);return u?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}function Cf(r,t,e,n,o,a){var i=C(r,"x","avgPool","float32");E(tt(e,n),(function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+n+"'"}));var s=i,u=!1;i.rank===3&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),E(s.rank===4,(function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."})),a!=null&&E(De(o),(function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."}));var c=er(s.shape,t,e,n,o,a);if(c.filterWidth===1&&c.filterHeight===1&&Ne(c.inShape,c.outShape))return i.clone();var l=A.runKernelFunc((function(h){return h.avgPool(s,c)}),{x:s},(function(h){return{x:function(){return(function(f,d,p,m,v,g){var x=C(f,"dy","avgPoolBackprop"),b=C(d,"input","avgPoolBackprop");E(b.rank===x.rank,(function(){return"Rank of input ("+b.rank+") does not match rank of dy ("+x.rank+")"})),E(tt(m,v),(function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+m+" and dilations '"+v+"'"}));var y=b,w=x,_=!1;b.rank===3&&(_=!0,y=b.as4D(1,b.shape[0],b.shape[1],b.shape[2]),w=x.as4D(1,x.shape[0],x.shape[1],x.shape[2])),E(w.rank===4,(function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+w.rank+"."})),E(y.rank===4,(function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+y.rank+"."}));var S=er(y.shape,p,m,v,g),k=A.runKernelFunc((function(I){return I.avgPoolBackprop(w,y,S)}),{dy4D:w,input4D:y});return _?k.as3D(k.shape[1],k.shape[2],k.shape[3]):k})(h,s,t,e,n,o)}}}),"AvgPool",c);return l=l.cast(i.dtype),u?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}var ze=D({maxPool_:function(r,t,e,n,o){return wf(r,t,e,1,n,o)}}),sr=D({avgPool_:function(r,t,e,n,o){return Cf(r,t,e,1,n,o)}}),_f=D({pool_:function(r,t,e,n,o,a){o==null&&(o=[1,1]),a==null&&(a=1),n===0&&(n="valid");var i=C(r,"x","maxPool"),s=i,u=!1;i.rank===3&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),E(tt(a,o),(function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'"}));var c,l=er(s.shape,t,a,o,n),h=[l.dilationHeight,l.dilationWidth];c=n==="same"?(function(y,w){var _=y.map((function(I,R){return I+(I-1)*(w[R]-1)})).map((function(I){return I-1})),S=_.map((function(I){return Math.floor(I/2)})),k=_.map((function(I,R){return I-S[R]}));return _.map((function(I,R){return[S[R],k[R]]}))})([l.filterHeight,l.filterWidth],h):[[0,0],[0,0]];var f=h[0]===1&&h[1]===1,d=(function(y,w,_){var S=_.map((function(O){return O[0]})),k=_.map((function(O){return O[1]})),I=y.concat(S,k),R=w.map((function(O,B){return(O-I[B]%O)%O})),F=k.map((function(O,B){return O+R[B]})),T=w.map((function(O,B){return[S[B],F[B]]})),L=w.map((function(O,B){return[0,R[B]]}));return[T,L]})([l.inHeight,l.inWidth],h,c),p=d[0],m=d[1],v=f?n:"valid",g=f?s:Ei(s,h,p),x=(e==="avg"?function(){return Cf(g,t,a,1,v)}:function(){return wf(g,t,a,1,v)})(),b=f?x:wi(x,h,m);return u?b.as3D(b.shape[1],b.shape[2],b.shape[3]):b}}),Ef=D({maxPool3d_:function(r,t,e,n,o,a,i){a===void 0&&(a="NDHWC");var s=C(r,"x","maxPool3d"),u=s,c=!1;s.rank===4&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),i==null&&(i=[1,1,1]),E(u.rank===5,(function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."})),E(a==="NDHWC",(function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+a})),E(tt(e,i),(function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+i+"'"})),o!=null&&E(De(n),(function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+n+"."}));var l=Ar(u.shape,t,e,i,n,o,a),h=A.runKernelFunc((function(f,d){var p=f.maxPool3d(u,l);return d([u,p]),p}),{x:u},(function(f,d){var p=d[0],m=d[1];return{x:function(){return(function(v,g,x,b,y,w,_,S){var k=C(v,"dy","maxPool3dBackprop"),I=C(g,"input","maxPool3dBackprop"),R=C(x,"output","maxPool3dBackprop"),F=k,T=I,L=R,O=!1;I.rank===4&&(O=!0,F=k.as5D(1,k.shape[0],k.shape[1],k.shape[2],k.shape[3]),T=I.as5D(1,I.shape[0],I.shape[1],I.shape[2],I.shape[3]),L=R.as5D(1,R.shape[0],R.shape[1],R.shape[2],R.shape[3])),E(F.rank===5,(function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+F.rank+"."})),E(T.rank===5,(function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+T.rank+"."})),E(L.rank===5,(function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+L.rank+"."})),w==null&&(w=[1,1,1]),E(tt(y,w),(function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+y+" and dilations '"+w+"'"})),S!=null&&E(De(_),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+S+" but got pad "+_+"."}));var B=Ar(T.shape,b,y,w,_,S),U=A.runKernelFunc((function(z){return z.maxPool3dBackprop(F,T,L,B)}),{dy5D:F,input5D:T});return O?U.as4D(U.shape[1],U.shape[2],U.shape[3],U.shape[4]):U})(f,p,m,t,e,i,n,o)}}}));return c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),If=D({avgPool3d_:function(r,t,e,n,o,a,i){a===void 0&&(a="NDHWC");var s=C(r,"x","avgPool3d","float32"),u=s,c=!1;s.rank===4&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),i==null&&(i=[1,1,1]),E(u.rank===5,(function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."})),E(a==="NDHWC",(function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+a})),E(tt(e,i),(function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+i+"'"})),o!=null&&E(De(n),(function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+n+"."}));var l=Ar(u.shape,t,e,i,n,o,a),h=A.runKernelFunc((function(f){return f.avgPool3d(u,l)}),{x:u},(function(f){return{x:function(){return(function(d,p,m,v,g,x,b){var y=C(d,"dy","avgPool3dBackprop"),w=C(p,"input","avgPool3dBackprop"),_=y,S=w,k=!1;w.rank===4&&(k=!0,_=y.as5D(1,y.shape[0],y.shape[1],y.shape[2],y.shape[3]),S=w.as5D(1,w.shape[0],w.shape[1],w.shape[2],w.shape[3])),E(_.rank===5,(function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+_.rank+"."})),E(S.rank===5,(function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+S.rank+"."})),g==null&&(g=[1,1,1]),E(tt(v,g),(function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+v+" and dilations '"+g+"'"})),b!=null&&E(De(x),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+b+" but got pad "+x+"."}));var I=Ar(S.shape,m,v,g,x,b),R=A.runKernelFunc((function(F){return F.avgPool3dBackprop(_,S,I)}),{dy5D:_,input5D:S});return k?R.as4D(R.shape[1],R.shape[2],R.shape[3],R.shape[4]):R})(f,u,t,e,i,n,o)}}}));return h=h.cast(u.dtype),c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),Ct=D({slice_:function(r,t,e){var n,o,a=C(r,"x","slice");if(a.rank===0)throw new Error("Slicing scalar is not possible");(n=typeof t=="number"?[t].concat(new Array(a.rank-1).fill(0)):t.length=0?u:(E(u===-1,(function(){return"Negative size values should be exactly -1 but got "+u+" for the slice() size at index "+c+"."})),a.shape[c]-n[c])})),cl(a,n,o);var i=a.shape,s={begin:n,size:o};return A.runKernelFunc((function(u){return u.slice(a,n,o)}),{x:a},(function(u){for(var c=[],l=0;l0&&(c=c.sum(l)),c.reshape(s.shape)}}}),"Prelu")}}),Ee=D({relu_:function(r){var t=C(r,"x","relu");return t.dtype==="bool"?t.toInt():A.runKernelFunc((function(e,n){var o=e.relu(t);return n([t]),o}),{x:t},(function(e,n){var o=n[0];return{x:function(){return e.mulStrict(o.step().toFloat())}}}),"Relu")}}),rs=D({relu6_:function(r){var t=C(r,"x","relu6");return t.dtype==="bool"?t.toInt():A.runKernelFunc((function(e,n){var o=e.relu6(t);return n([t]),o}),{x:t},(function(e,n){var o=n[0],a=o.lessEqual(6).mul(o.step());return{x:function(){return e.mulStrict(a.toFloat())}}}),"Relu6")}}),zf=D({selu_:function(r){var t=C(r,"x","selu");return A.runKernelFunc((function(e,n){var o=e.selu(t);return n([t]),o}),{$x:t},(function(e,n){var o=n[0];return{$x:function(){var a=o.greater(q(0)),i=q(Wi),s=q(zi),u=e.mul(s),c=e.mul(i).mul(o.toFloat().exp());return dn(a,u,c)}}}))}}),$t=D({transpose_:function(r,t){var e=C(r,"x","transpose");if(t==null&&(t=e.shape.map((function(o,a){return a})).reverse()),E(e.rank===t.length,(function(){return"Error in transpose: rank of input "+e.rank+" must match length of perm "+t+"."})),t.forEach((function(o){E(o>=0&&oo)throw new Error("'k' passed to topk() must be <= the last dimension ("+o+") but got "+t);var a=A.runKernelFunc((function(i){return i.topk(n,t,e)}),{$x:n});return{values:a[0],indices:a[1]}}}),Kf=D({scatterND_:function(r,t,e){var n=C(r,"indices","scatterND","int32"),o=C(t,"updates","scatterND");return ul(o,n,e),A.runKernelFunc((function(a){return a.scatterND(n,o,e)}),{indices:n,updates:o},null,"ScatterNd",{shape:e})}}),Ho=D({fft_:function(r){E(r.dtype==="complex64",(function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+r.dtype+"."}));var t=r.shape[r.shape.length-1],e=r.size/t,n=r.as2D(e,t);return A.runKernelFunc((function(o){return o.fft(n)}),{input:r}).reshape(r.shape)}}),Pr=D({ifft_:function(r){E(r.dtype==="complex64",(function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+r.dtype+"."}));var t=r.shape[r.shape.length-1],e=r.size/t,n=r.as2D(e,t);return A.runKernelFunc((function(o){return o.ifft(n)}),{input:r}).reshape(r.shape)}}),qo=D({rfft_:function(r,t){E(r.dtype==="float32",(function(){return"The dtype for rfft() must be real value but got "+r.dtype}));var e,n=r.shape[r.shape.length-1],o=r.size/n;if(t!=null&&tn){var s=r.shape.map((function(g){return g}));s[r.shape.length-1]=t-n,e=r.concat(Ce(s),r.shape.length-1),n=t}else e=r;var u=e.zerosLike(),c=Ue(e,u).as2D(o,n),l=Ho(c),h=Math.floor(n/2)+1,f=ut(l),d=yt(l),p=f.split([h,n-h],f.shape.length-1),m=d.split([h,n-h],d.shape.length-1),v=e.shape.slice();return v[e.shape.length-1]=h,Ue(p[0],m[0]).reshape(v)}}),as=D({irfft_:function(r){var t=r.shape[r.shape.length-1],e=r.size/t;if(t<=2){var n=r.as2D(e,t),o=Pr(n);return ut(o)}var a=[e,2*(t-1)],i=ut(r).as2D(e,t),s=yt(r).as2D(e,t),u=i.slice([0,1],[e,t-2]).reverse(1),c=s.slice([0,1],[e,t-2]).reverse(1).mul(q(-1)),l=i.concat(u,1),h=s.concat(c,1);return n=Ue(l,h).as2D(a[0],a[1]),o=Pr(n),ut(o)}}),Xf=Object.freeze({fft:Ho,ifft:Pr,rfft:qo,irfft:as}),Yf=D({sparseToDense_:function(r,t,e,n){n===void 0&&(n=0);var o=C(r,"sparseIndices","sparseToDense","int32"),a=C(t,"sparseValues","sparseToDense"),i=C(n,"defaultValue","sparseToDense",a.dtype);return(function(s,u,c,l){if(s.dtype!=="int32")throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+s.dtype+".");if(s.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+s.shape+".");var h=s.rank>0?s.shape[0]:1,f=s.rank>1?s.shape[1]:1;if(c.length!==f)throw new Error("outputShape has incorrect number of elements:, "+c.length+", should be: "+f+".");var d=u.size;if(u.rank!==0&&(u.rank!==1||d!==h))throw new Error("sparseValues has incorrect shape "+u.shape+", should be [] or ["+h+"]");if(u.dtype!==l.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")})(o,a,e,i),A.runKernelFunc((function(s){return s.sparseToDense(o,a,e,i)}),{$sparseIndices:o,$sparseValues:a,$defaultValue:i})}}),$f=D({gatherND_:function(r,t){var e=C(t,"indices","gatherND","int32"),n=C(r,"x","gatherND");return A.runKernelFunc((function(o){return o.gatherND(n,e)}),{x:n,indices:e},null,"GatherNd")}}),Jf=D({diag_:function(r){var t=C(r,"x","diag").flatten(),e=r.shape.concat(r.shape);return A.runKernelFunc((function(n){return n.diag(t)}),{$x:t}).reshape(e)}}),Qf=D({dropout_:function(r,t,e,n){var o=C(r,"x","dropout");if(E(o.dtype==="float32",(function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+o.dtype+" tensor instead."})),E(t>=0&&t<1,(function(){return"rate must be a float in the range [0, 1), but got "+t+"."})),t===0)return r instanceof we?o.clone():o;var a=(function(u,c){if(c==null)return u.shape.slice();if(Ne(u.shape,c))return c;if(u.shape.length===c.length){for(var l=[],h=0;h1,(function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+n.rank})),E(n.rank-1===o.rank,(function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+n.rank+" and targets rank "+o.rank})),me(n.shape.slice(0,n.shape.length-1),o.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),a=n.shape[n.shape.length-1],E(e>0&&e<=a,(function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+a+"), but got "+e})),[4,n.data()];case 1:return i=g.sent(),[4,o.data()];case 2:for(s=g.sent(),u=[i.length/a,a],l=u[1],h=Qn("bool",c=u[0]),f=0;f1?s.div(q(i)):s}if(e===Ke.SUM_BY_NONZERO_WEIGHTS){if(o==null)return a.sum().div(q(n.size));var u=o.mul(Nn(n.shape)).notEqual(q(0)).sum().toFloat();return a.sum().div(u)}throw Error("Unknown reduction: "+e)}}),Wm=D({cosineDistance_:function(r,t,e,n,o){o===void 0&&(o=Ke.SUM_BY_NONZERO_WEIGHTS);var a=C(r,"labels","cosineDistance"),i=C(t,"predictions","cosineDistance"),s=null;n!=null&&(s=C(n,"weights","cosineDistance")),me(a.shape,i.shape,"Error in cosineDistance: ");var u=q(1).sub(a.mul(i).sum(e,!0));return Qt(u,s,o)}}),zm=D({hingeLoss_:function(r,t,e,n){n===void 0&&(n=Ke.SUM_BY_NONZERO_WEIGHTS);var o=C(r,"labels","hingeLoss"),a=C(t,"predictions","hingeLoss"),i=null;e!=null&&(i=C(e,"weights","hingeLoss")),me(o.shape,a.shape,"Error in hingeLoss: ");var s=q(1);o=q(2).mul(o).sub(s);var u=s.sub(o.mul(a)).relu();return Qt(u,i,n)}}),Um=D({huberLoss_:function(r,t,e,n,o){n===void 0&&(n=1),o===void 0&&(o=Ke.SUM_BY_NONZERO_WEIGHTS);var a=C(r,"labels","huberLoss"),i=C(t,"predictions","huberLoss"),s=null;e!=null&&(s=C(e,"weights","huberLoss")),me(a.shape,i.shape,"Error in huberLoss: ");var u=q(n),c=i.sub(a).abs(),l=Xi(c,u),h=c.sub(l),f=q(.5).mul(l.square()).add(u.mul(h));return Qt(f,s,o)}}),Vm=D({logLoss_:function(r,t,e,n,o){n===void 0&&(n=1e-7),o===void 0&&(o=Ke.SUM_BY_NONZERO_WEIGHTS);var a=C(r,"labels","logLoss"),i=C(t,"predictions","logLoss"),s=null;e!=null&&(s=C(e,"weights","logLoss")),me(a.shape,i.shape,"Error in logLoss: ");var u=q(1),c=q(n),l=a.mul(i.add(c).log()).neg().sub(u.sub(a).mul(u.sub(i).add(c).log()));return Qt(l,s,o)}}),Gm=D({meanSquaredError_:function(r,t,e,n){n===void 0&&(n=Ke.SUM_BY_NONZERO_WEIGHTS);var o=C(r,"labels","meanSquaredError"),a=C(t,"predictions","meanSquaredError"),i=null;e!=null&&(i=C(e,"weights","meanSquaredError")),me(o.shape,a.shape,"Error in meanSquaredError: ");var s=o.squaredDifference(a);return Qt(s,i,n)}}),Hm=D({sigmoidCrossEntropy_:function(r,t,e,n,o){n===void 0&&(n=0),o===void 0&&(o=Ke.SUM_BY_NONZERO_WEIGHTS);var a=C(r,"multiClassLabels","sigmoidCrossEntropy"),i=C(t,"logits","sigmoidCrossEntropy"),s=null;if(e!=null&&(s=C(e,"weights","sigmoidCrossEntropy")),me(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),n>0){var u=q(n),c=q(1),l=q(.5);a=a.mul(c.sub(u)).add(l.mul(u))}var h=(function(f,d){var p=C(f,"labels","sigmoidCrossEntropyWithLogits"),m=C(d,"logits","sigmoidCrossEntropyWithLogits");me(p.shape,m.shape,"Error in sigmoidCrossEntropyWithLogits: ");var v=m.relu(),g=m.mul(p),x=m.abs().neg().exp().log1p();return v.sub(g).add(x)})(a,i);return Qt(h,s,o)}}),qm=D({softmaxCrossEntropy_:function(r,t,e,n,o){n===void 0&&(n=0),o===void 0&&(o=Ke.SUM_BY_NONZERO_WEIGHTS);var a=C(r,"onehotLabels","softmaxCrossEntropy"),i=C(t,"logits","softmaxCrossEntropy"),s=null;if(e!=null&&(s=C(e,"weights","softmaxCrossEntropy")),me(a.shape,i.shape,"Error in softmaxCrossEntropy: "),n>0){var u=q(n),c=q(1),l=q(a.shape[1]);a=a.mul(c.sub(u)).add(u.div(l))}var h=(function(f,d,p){if(p===void 0&&(p=-1),p===-1&&(p=d.rank-1),p!==d.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+d.rank+" and dim was "+p);return Wr((function(m,v,g){var x=v.logSumExp([p],!0),b=v.toFloat().sub(x);return g([m,b]),{value:b.mul(m).neg().sum([p]),gradFunc:function(y,w){var _=w[0],S=w[1],k=et(y.shape,[p]);return[y.reshape(k).mul(_.toFloat().sub(S.exp())),y.reshape(k).mul(S.exp().sub(_.toFloat()))]}}}))(f,d)})(a,i);return Qt(h,s,o)}}),nd=Object.freeze({get Reduction(){return Ke},absoluteDifference:Lm,computeWeightedLoss:Qt,cosineDistance:Wm,hingeLoss:zm,huberLoss:Um,logLoss:Vm,meanSquaredError:Gm,sigmoidCrossEntropy:Hm,softmaxCrossEntropy:qm});function Eu(r,t){return t===void 0&&(t=!1),A.tidy((function(){if(r.shape.length!==2)throw new Error("qr2d() requires a 2D Tensor, but got a "+r.shape.length+"D Tensor.");for(var e=r.shape[0],n=r.shape[1],o=Ci(e),a=r.clone(),i=Kt([[1]],[1,1]),s=i.clone(),u=e>=n?n:e,c=function(h){var f,d=a,p=s,m=o;f=A.tidy((function(){var v=a.slice([h,h],[e-h,1]),g=v.norm(),x=a.slice([h,h],[1,1]),b=Kt([[-1]]).where(x.greater(0),Kt([[1]])),y=x.sub(b.mul(g)),w=v.div(y);s=w.shape[0]===1?i.clone():i.concat(w.slice([1,0],[w.shape[0]-1,w.shape[1]]),0);var _=b.matMul(y).div(g).neg(),S=a.slice([h,0],[e-h,n]),k=_.mul(s);if(h===0)a=S.sub(k.matMul(s.transpose().matMul(S)));else{var I=S.sub(k.matMul(s.transpose().matMul(S)));a=a.slice([0,0],[h,n]).concat(I,0)}var R=o.slice([0,h],[e,o.shape[1]-h]);if(h===0)o=R.sub(R.matMul(s).matMul(k.transpose()));else{var F=R.sub(R.matMul(s).matMul(k.transpose()));o=o.slice([0,0],[e,h]).concat(F,1)}return[s,a,o]})),s=f[0],a=f[1],o=f[2],Ze([d,p,m])},l=0;ln&&(o=o.slice([0,0],[e,n]),a=a.slice([0,0],[n,n])),[o,a]}))}var jm=D({bandPart_:function(r,t,e){if(t%1!=0)throw new Error("bandPart(): numLower must be an integer, got "+t+".");if(e%1!=0)throw new Error("bandPart(): numUpper must be an integer, got "+e+".");var n=C(r,"a","bandPart");if(n.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+n.rank+".");var o=n.shape,a=n.shape.slice(-2),i=a[0],s=a[1];if(!(t<=i))throw new Error("bandPart(): numLower ("+t+") must not be greater than the number of rows ("+i+").");if(!(e<=s))throw new Error("bandPart(): numUpper ("+e+") must not be greater than the number of columns ("+s+").");t<0&&(t=i),e<0&&(e=s);var u=kr(0,i,1,"int32").reshape([-1,1]),c=kr(0,s,1,"int32"),l=Be(u,c),h=Vr(l.lessEqual(q(+t,"int32")),l.greaterEqual(q(-e,"int32"))),f=Ce([i,s],n.dtype);return ot(Me(n.reshape([-1,i,s])).map((function(d){return dn(h,d,f)}))).reshape(o)}}),Km=D({gramSchmidt_:function(r){var t;if(Array.isArray(r)){t=!1,E(r!=null&&r.length>0,(function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"}));for(var e=r[0].shape[0],n=function(u){E(r[u].shape[0]===e,(function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+r[u].shape[0]+" vs. "+e+")"}))},o=1;o0)for(var l=0;l= 2, but got rank "+r.rank);if(r.rank===2)return Eu(r,t);var e=r.shape.slice(0,r.shape.length-2).reduce((function(i,s){return i*s})),n=Me(r.reshape([e,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),o=[],a=[];return n.forEach((function(i){var s=Eu(i,t),u=s[0],c=s[1];o.push(u),a.push(c)})),[ot(o,0).reshape(r.shape),ot(a,0).reshape(r.shape)]}}),rd=Object.freeze({bandPart:jm,gramSchmidt:Km,qr:Xm});function Xo(r,t,e,n,o,a){n==null&&(n=.5),o==null&&(o=Number.NEGATIVE_INFINITY),a==null&&(a=0);var i=r.shape[0];return e=Math.min(e,i),E(0<=n&&n<=1,(function(){return"iouThreshold must be in [0, 1], but was '"+n+"'"})),E(r.rank===2,(function(){return"boxes must be a 2D tensor, but was of rank '"+r.rank+"'"})),E(r.shape[1]===4,(function(){return"boxes must have 4 columns, but 2nd dimension was "+r.shape[1]})),E(t.rank===1,(function(){return"scores must be a 1D tensor"})),E(t.shape[0]===i,(function(){return"scores has incompatible shape with boxes. Expected "+i+", but was "+t.shape[0]})),E(0<=a&&a<=1,(function(){return"softNmsSigma must be in [0, 1], but was '"+a+"'"})),{maxOutputSize:e,iouThreshold:n,scoreThreshold:o,softNmsSigma:a}}var Ym=D({resizeBilinear_:function(r,t,e){e===void 0&&(e=!1);var n=C(r,"images","resizeBilinear");E(n.rank===3||n.rank===4,(function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+n.rank+"."})),E(t.length===2,(function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+t+"."}));var o=n,a=!1;n.rank===3&&(a=!0,o=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]));var i=t[0],s=t[1],u=A.runKernelFunc((function(c,l){return l([o]),c.resizeBilinear(o,i,s,e)}),{x:o},(function(c,l){return{x:function(){return A.runKernelFunc((function(h){return h.resizeBilinearBackprop(c,l[0],e)}),{})}}}),"ResizeBilinear",{alignCorners:e,newHeight:i,newWidth:s});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),$m=D({resizeNearestNeighbor_:function(r,t,e){e===void 0&&(e=!1);var n=C(r,"images","resizeNearestNeighbor");E(n.rank===3||n.rank===4,(function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+n.rank+"."})),E(t.length===2,(function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+t+"."})),E(n.dtype==="float32"||n.dtype==="int32",(function(){return"`images` must have `int32` or `float32` as dtype"}));var o=n,a=!1;n.rank===3&&(a=!0,o=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]));var i=t[0],s=t[1],u=A.runKernelFunc((function(c,l){return l([o]),c.resizeNearestNeighbor(o,i,s,e)}),{batchImages:o},(function(c,l){return{batchImages:function(){return A.runKernelFunc((function(h){return h.resizeNearestNeighborBackprop(c,l[0],e)}),{})}}}));return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Jm=D({nonMaxSuppression_:function(r,t,e,n,o){n===void 0&&(n=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY);var a=C(r,"boxes","nonMaxSuppression"),i=C(t,"scores","nonMaxSuppression"),s=Xo(a,i,e,n,o);e=s.maxOutputSize,n=s.iouThreshold,o=s.scoreThreshold;var u={maxOutputSize:e,iouThreshold:n,scoreThreshold:o};return A.runKernelFunc((function(c){return c.nonMaxSuppression(a,i,e,n,o)}),{boxes:a,scores:i},null,"NonMaxSuppressionV3",u)}}),Qm=function(r,t,e,n,o){return n===void 0&&(n=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY),J(this,void 0,void 0,(function(){var a,i,s,u,c,l,h;return Q(this,(function(f){switch(f.label){case 0:return a=C(r,"boxes","nonMaxSuppressionAsync"),i=C(t,"scores","nonMaxSuppressionAsync"),s=Xo(a,i,e,n,o),e=s.maxOutputSize,n=s.iouThreshold,o=s.scoreThreshold,[4,Promise.all([a.data(),i.data()])];case 1:return u=f.sent(),c=u[0],l=u[1],h=Mi(c,l,e,n,o),a!==r&&a.dispose(),i!==t&&i.dispose(),[2,h]}}))}))},Zm=D({nonMaxSuppressionWithScore_:function(r,t,e,n,o,a){n===void 0&&(n=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY),a===void 0&&(a=0);var i=C(r,"boxes","nonMaxSuppression"),s=C(t,"scores","nonMaxSuppression"),u=Xo(i,s,e,n,o,a),c={maxOutputSize:e=u.maxOutputSize,iouThreshold:n=u.iouThreshold,scoreThreshold:o=u.scoreThreshold,softNmsSigma:a=u.softNmsSigma},l=A.runKernel("NonMaxSuppressionV5",{boxes:i,scores:s},c);return{selectedIndices:l[0],selectedScores:l[1]}}}),eg=function(r,t,e,n,o,a){return n===void 0&&(n=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY),a===void 0&&(a=0),J(this,void 0,void 0,(function(){var i,s,u,c,l,h,f;return Q(this,(function(d){switch(d.label){case 0:return i=C(r,"boxes","nonMaxSuppressionAsync"),s=C(t,"scores","nonMaxSuppressionAsync"),u=Xo(i,s,e,n,o,a),e=u.maxOutputSize,n=u.iouThreshold,o=u.scoreThreshold,a=u.softNmsSigma,[4,Promise.all([i.data(),s.data()])];case 1:return c=d.sent(),l=c[0],h=c[1],f=Oi(l,h,e,n,o,a),i!==r&&i.dispose(),s!==t&&s.dispose(),[2,f]}}))}))},tg=D({cropAndResize_:function(r,t,e,n,o,a){var i=C(r,"image","cropAndResize"),s=C(t,"boxes","cropAndResize","float32"),u=C(e,"boxInd","cropAndResize","int32");o=o||"bilinear",a=a||0;var c=s.shape[0];return E(i.rank===4,(function(){return"Error in cropAndResize: image must be rank 4,but got rank "+i.rank+"."})),E(s.rank===2&&s.shape[1]===4,(function(){return"Error in cropAndResize: boxes must be have size ["+c+",4] but had shape "+s.shape+"."})),E(u.rank===1&&u.shape[0]===c,(function(){return"Error in cropAndResize: boxInd must be have size ["+c+"] but had shape "+s.shape+"."})),E(n.length===2,(function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+n.length+"."})),E(n[0]>=1&&n[1]>=1,(function(){return"cropSize must be atleast [1,1], but was "+n})),E(o==="bilinear"||o==="nearest",(function(){return"method must be bilinear or nearest, but was "+o})),A.runKernelFunc((function(l,h){return l.cropAndResize(i,s,u,n,o,a)}),{images:i,boxes:s,boxInd:u},null,"CropAndResize",{method:o,extrapolationValue:a,cropSize:n})}}),Yo=Object.freeze({resizeBilinear:Ym,resizeNearestNeighbor:$m,nonMaxSuppression:Jm,nonMaxSuppressionAsync:Qm,nonMaxSuppressionWithScore:Zm,nonMaxSuppressionWithScoreAsync:eg,cropAndResize:tg}),us=function(r,t){return!(r>0)||t==="linear"},cs=function(r,t,e){if(e==null||e==="linear")return r;if(e==="relu")return r.mul(t.step());throw new Error("Gradient for activation "+e+" has not been implemented yet.")},ls=function(r,t){var e=t,n=Oe(r.shape,t.shape);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},hs=function(r,t,e){if(t==="linear")return r;if(t==="relu")return Ee(r);if(t==="elu")return ts(r);if(t==="relu6")return rs(r);if(t==="prelu")return ns(r,e);throw new Error("Unknown fused activation "+t+".")},ng=D({fusedMatMul_:function(r){var t,e=r.a,n=r.b,o=r.transposeA,a=o!==void 0&&o,i=r.transposeB,s=i!==void 0&&i,u=r.bias,c=r.activation,l=c===void 0?"linear":c,h=r.preluActivationWeights;if(us(A.state.gradientDepth,l)===!1){var f=Hr(e,n,a,s);return u!=null&&(f=ue(f,u)),hs(f,l,h)}var d=C(e,"a","fused matMul"),p=C(n,"b","fused matMul");t=Ie(d,p),d=t[0],p=t[1];var m=a?d.shape[d.rank-2]:d.shape[d.rank-1],v=s?p.shape[p.rank-1]:p.shape[p.rank-2],g=a?d.shape[d.rank-1]:d.shape[d.rank-2],x=s?p.shape[p.rank-2]:p.shape[p.rank-1],b=d.shape.slice(0,-2),y=p.shape.slice(0,-2),w=Z(b),_=Z(y);E(d.rank>=2&&p.rank>=2&&d.rank===p.rank,(function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+d.rank+" and "+p.rank+"."})),E(Ne(b,y),(function(){return"Error in fused matMul: outer dimensions ("+b+") and ("+y+") of Tensors with shapes "+d.shape+" and "+p.shape+" must match."})),E(m===v,(function(){return"Error in fused matMul: inner shapes ("+m+") and ("+v+") of Tensors with shapes "+d.shape+" and "+p.shape+" and transposeA="+a+" and transposeB="+s+" must match."}));var S,k,I=d.shape.slice(0,-2).concat([g,x]),R=a?d.as3D(w,m,g):d.as3D(w,g,m),F=s?p.as3D(_,x,v):p.as3D(_,v,x);u!=null&&ce(I,(S=Ie(S=C(u,"bias","fused matMul"),d)[0]).shape),h!=null&&(k=C(h,"prelu weights","fused matMul"));var T={a:R,b:F};u!=null&&(T.bias=S),h!=null&&(T.preluActivationWeights=k);var L=[R,F];return A.runKernelFunc((function(O,B){var U=O.fusedBatchMatMul({a:R,b:F,transposeA:a,transposeB:s,bias:S,activation:l,preluActivationWeights:k});return B([R,F,U]),U}),T,(function(O,B){var U=B[0],z=B[1],W=B[2],G=cs(O,W,l),H={};return u!=null&&(H={bias:function(){return ls(S,G)}}),Object.assign(a||s?!a&&s?{a:function(){return G.matMul(z,!1,!1)},b:function(){return G.matMul(U,!0,!1)}}:a&&!s?{a:function(){return z.matMul(G,!1,!0)},b:function(){return U.matMul(G,!1,!1)}}:{a:function(){return z.matMul(G,!0,!0)},b:function(){return G.matMul(U,!0,!0)}}:{a:function(){return G.matMul(z,!1,!0)},b:function(){return U.matMul(G,!0,!1)}},H)}),"_FusedMatMul",{transposeA:a,transposeB:s,activation:l},L,[!0]).reshape(I)}}),rg=D({fusedConv2d_:function(r){var t=r.x,e=r.filter,n=r.strides,o=r.pad,a=r.dataFormat,i=a===void 0?"NHWC":a,s=r.dilations,u=s===void 0?[1,1]:s,c=r.dimRoundingMode,l=r.bias,h=r.activation,f=h===void 0?"linear":h,d=r.preluActivationWeights;if(f=f||"linear",us(A.state.gradientDepth,f)===!1){var p=pt(t,e,n,o,i,u,c);return l!=null&&(p=ue(p,l)),hs(p,f,d)}var m=C(t,"x","conv2d"),v=C(e,"filter","conv2d"),g=m,x=!1;m.rank===3&&(x=!0,g=m.as4D(1,m.shape[0],m.shape[1],m.shape[2])),E(g.rank===4,(function(){return"Error in fused conv2d: input must be rank 4, but got rank "+g.rank+"."})),E(v.rank===4,(function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+v.rank+"."})),c!=null&&E(De(o),(function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+c+" but got pad "+o+"."})),E(g.shape[3]===v.shape[2],(function(){return"Error in conv2d: depth of input ("+g.shape[3]+") must match input depth for filter "+v.shape[2]+"."})),E(tt(n,u),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+u+"'"})),E(i==="NHWC",(function(){return"Error in conv2d: got dataFormat of "+i+" but only NHWC is currently supported."}));var b,y,w=mn(g.shape,v.shape,n,u,o,c);l!=null&&(b=Ie(b=C(l,"bias","fused conv2d"),m)[0],ce(w.outShape,b.shape)),d!=null&&(y=C(d,"prelu weights","fused conv2d"));var _={x:g,filter:v};l!=null&&(_.bias=b),d!=null&&(_.preluActivationWeights=y);var S=[v,g],k=A.runKernelFunc((function(I,R){var F=I.fusedConv2d({input:g,filter:v,convInfo:w,bias:b,activation:f,preluActivationWeights:y});return R([v,g,F]),F}),_,(function(I,R){var F=R,T=F[0],L=F[1],O=F[2],B=cs(I,O,f);E(Tn(u),(function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"}));var U={};return l!=null&&(U={bias:function(){return ls(b,B)}}),Object.assign({x:function(){return lf(L.shape,B,T,n,o)},filter:function(){return Qi(L,B,T.shape,n,o)}},U)}),"FusedConv2D",{convInfo:w,activation:f},S,[!0]);return x?k.as3D(k.shape[1],k.shape[2],k.shape[3]):k}}),og=D({fusedDepthwiseConv2d_:function(r){var t=r.x,e=r.filter,n=r.strides,o=r.pad,a=r.dataFormat,i=a===void 0?"NHWC":a,s=r.dilations,u=s===void 0?[1,1]:s,c=r.dimRoundingMode,l=r.bias,h=r.activation,f=h===void 0?"linear":h,d=r.preluActivationWeights;if(us(A.state.gradientDepth,f)===!1){var p=Gr(t,e,n,o,i,u,c);return l!=null&&(p=ue(p,l)),hs(p,f,d)}var m=C(t,"x","depthwiseConv2d"),v=C(e,"filter","depthwiseConv2d"),g=m,x=!1;m.rank===3&&(x=!0,g=m.as4D(1,m.shape[0],m.shape[1],m.shape[2])),E(g.rank===4,(function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+g.rank+"."})),E(v.rank===4,(function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+v.rank+"."})),E(g.shape[3]===v.shape[2],(function(){return"Error in fused depthwiseConv2d: number of input channels ("+g.shape[3]+") must match the inChannels dimension in filter "+v.shape[2]+"."})),u==null&&(u=[1,1]),E(tt(n,u),(function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+u+"'"})),c!=null&&E(De(o),(function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+c+" but got pad "+o+"."}));var b,y,w=mn(g.shape,v.shape,n,u,o,c,!0);l!=null&&(b=Ie(b=C(l,"bias","fused conv2d"),m)[0],ce(w.outShape,b.shape)),d!=null&&(y=C(d,"prelu weights","fused depthwiseConv2d"));var _={x:g,filter:v};l!=null&&(_.bias=b),d!=null&&(_.preluActivationWeights=y);var S=[v,g],k=A.runKernelFunc((function(I,R){var F=I.fusedDepthwiseConv2D({input:g,filter:v,convInfo:w,bias:b,activation:f,preluActivationWeights:y});return R([v,g,F]),F}),_,(function(I,R){E(Tn(u),(function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+u+"'"}));var F=R[0],T=R[1],L=R[2],O=cs(I,L,f),B={};return l!=null&&(B={bias:function(){return ls(b,O)}}),Object.assign({x:function(){return hf(T.shape,O,F,w)},filter:function(){return ff(T,O,F.shape,w)}},B)}),"FusedDepthwiseConv2D",{convInfo:w,activation:f},S,[!0]);return x?k.as3D(k.shape[1],k.shape[2],k.shape[3]):k}}),od=Object.freeze({matMul:ng,conv2d:rg,depthwiseConv2d:og}),ag=Object.freeze({image:Yo,linalg:rd,losses:nd,spectral:Xf,fused:od,signal:ed,square:Kl,squaredDifference:Ui,conv1d:uf,conv2d:pt,conv3d:cf,depthwiseConv2d:Gr,separableConv2d:Go,conv2dTranspose:df,conv3dTranspose:pf,op:D,batchNormalization2d:Rh,batchNormalization3d:kh,batchNormalization4d:Sh,batchNormalization:Ah,batchNorm:Hi,batchNorm2d:Dh,batchNorm3d:Th,batchNorm4d:Fh,booleanMaskAsync:of,complex:Ue,real:ut,imag:yt,concat:Pe,concat1d:Wc,concat2d:zc,concat3d:Uc,concat4d:Vc,split:Po,matMul:Hr,dot:vf,outerProduct:mf,reverse:ir,reverse1d:gf,reverse2d:yf,reverse3d:xf,reverse4d:bf,maxPool:ze,avgPool:sr,pool:_f,maxPool3d:Ef,avgPool3d:If,slice:Ct,slice1d:Rf,slice2d:kf,slice3d:Zi,slice4d:Sf,abs:Xl,acos:Yl,acosh:$l,asin:Jl,asinh:Ql,atan:Zl,atanh:eh,ceil:th,clipByValue:Wo,cos:nh,cosh:rh,erf:oh,exp:Ro,expm1:ah,floor:ih,log:sh,log1p:uh,logSigmoid:ch,neg:Fr,reciprocal:lh,round:hh,rsqrt:Vi,sigmoid:Gi,sign:fh,isNaN:dh,isInf:ph,isFinite:vh,sin:mh,sinh:gh,softplus:yh,sqrt:xh,step:bh,tan:wh,tanh:Ch,all:Df,any:Tf,argMax:Ff,argMin:Nf,logSumExp:Pf,max:qr,mean:Mf,min:Of,moments:Bf,sum:es,prod:Lf,equal:Yi,equalStrict:Xh,greater:Yh,greaterEqual:$i,greaterEqualStrict:$h,greaterStrict:Jh,less:Qh,lessEqual:Zh,lessEqualStrict:ef,lessStrict:tf,notEqual:nf,notEqualStrict:rf,add:ue,addN:Mh,addStrict:Oh,atan2:Bh,div:vt,divNoNan:Lh,divStrict:Wh,floorDiv:Ki,maximum:Uo,maximumStrict:zh,minimum:Xi,minimumStrict:Uh,mod:Vh,modStrict:Gh,mul:Xe,mulStrict:Hh,pow:Nr,powStrict:qh,squaredDifferenceStrict:jh,sub:Be,subStrict:Kh,elu:ts,leakyRelu:Wf,prelu:ns,relu:Ee,relu6:rs,selu:zf,logicalAnd:Vr,logicalNot:Nh,logicalOr:qi,logicalXor:Ph,where:dn,whereAsync:ji,buffer:re,print:Gc,batchToSpaceND:wi,broadcastTo:Hc,cast:qc,clone:jc,cumsum:Kc,depthToSpace:Xc,expandDims:st,eye:Ci,multinomial:Yc,oneHot:bo,pad:vn,pad1d:$c,pad2d:Jc,pad3d:Qc,pad4d:Zc,rand:el,randomNormal:tl,randomGamma:nl,randomUniform:_i,reshape:mt,spaceToBatchND:Ei,squeeze:Ii,stack:ot,tile:kn,truncatedNormal:rl,unstack:Me,setdiff1dAsync:ol,fill:bt,linspace:Lc,ones:Nn,range:kr,scalar:q,tensor:Ge,tensor1d:Fe,tensor2d:Kt,tensor3d:No,tensor4d:Qe,tensor5d:Mc,tensor6d:Oc,variable:Bc,zeros:Ce,onesLike:xi,zerosLike:de,transpose:$t,softmax:Lt,logSoftmax:dl,localResponseNormalization:Uf,norm:os,gather:Vo,unsortedSegmentSum:Ji,basicLSTMCell:Vf,multiRNNCell:Gf,movingAverage:Hf,stridedSlice:qf,topk:jf,scatterND:Kf,fft:Ho,ifft:Pr,rfft:qo,irfft:as,sparseToDense:Yf,gatherND:$f,diag:Jf,dropout:Qf,hannWindow:jo,hammingWindow:is,frame:Ko,stft:ss,inTopKAsync:td});function V(r,t){Array.isArray(r)||(r=[r]),r.forEach((function(e){e!=null&&E(e.dtype!=="complex64",(function(){return t+" does not support complex64 tensors."}))}))}function wa(r,t,e,n){if(e==="linear")return r.linear(t);if(e==="relu")return r.relu(t);if(e==="elu")return r.elu(t);if(e==="relu6")return r.relu6(t);if(e==="prelu")return r.prelu(t,n);throw new Error("Activation "+e+" has not been implemented for the CPU backend.")}var ig=(function(r){function t(){var e=r.call(this)||this;return e.blockSize=48,e.firstUse=!0,e.data=new Di(e,A),e}return _t(t,r),t.prototype.write=function(e,n,o){this.firstUse&&(this.firstUse=!1,M().get("IS_NODE")&&xo(` +============================ +Hi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details. +============================`));var a={};return this.data.set(a,{values:e,dtype:o}),a},t.prototype.move=function(e,n,o,a){this.data.set(e,{values:n,dtype:a})},t.prototype.numDataIds=function(){return this.data.numDataIds()},t.prototype.read=function(e){return J(this,void 0,void 0,(function(){return Q(this,(function(n){return[2,this.readSync(e)]}))}))},t.prototype.readSync=function(e){var n=this.data.get(e),o=n.dtype,a=n.complexTensors;return o==="complex64"?Ya(this.readSync(a.real.dataId),this.readSync(a.imag.dataId)):this.data.get(e).values},t.prototype.bufferSync=function(e){var n=this.readSync(e.dataId),o=n;if(e.dtype==="string")try{o=n.map((function(a){return Cr(a)}))}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return re(e.shape,e.dtype,o)},t.prototype.makeOutput=function(e,n,o){var a=this.write(e,n,o);return A.makeTensorFromDataId(a,n,o,this)},t.prototype.disposeData=function(e){if(this.data.has(e)){var n=this.data.get(e).complexTensors;n!=null&&(n.real.dispose(),n.imag.dispose()),this.data.delete(e)}},t.prototype.time=function(e){return J(this,void 0,void 0,(function(){var n;return Q(this,(function(o){return n=gt(),e(),[2,{kernelMs:gt()-n}]}))}))},t.prototype.memory=function(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}},t.prototype.complex=function(e,n){var o=this.makeOutput(null,e.shape,"complex64");return this.data.get(o.dataId).complexTensors={real:A.keep(e.clone()),imag:A.keep(n.clone())},o},t.prototype.real=function(e){return this.data.get(e.dataId).complexTensors.real.clone()},t.prototype.imag=function(e){return this.data.get(e.dataId).complexTensors.imag.clone()},t.prototype.slice=function(e,n,o){if(V(e,"slice"),Si(e.shape,n,o)){var a=Ai(n,e.strides),i=Z(o);return Ge(this.readSync(e.dataId).subarray(a,a+i),o,e.dtype)}for(var s=re(o,e.dtype),u=this.bufferSync(e),c=0;cp&&(p=g,m=v)}l[f]=m}return u},t.prototype.cumsum=function(e,n,o,a){if(V(e,"cumsum"),n!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" but got axis="+n);for(var i=Ve(e.dtype,"int32"),s=Ce(e.shape,i),u=this.readSync(s.dataId),c=this.readSync(e.dataId),l=e.shape[e.rank-1],h=a?function(v,g){return v+l-g-1}:function(v,g){return v+g},f=0;fa?1:0}))},t.prototype.greaterEqual=function(e,n){return V([e,n],"greaterEqual"),this.broadcastedBinaryOp(e,n,"bool",(function(o,a){return o>=a?1:0}))},t.prototype.logicalNot=function(e){V(e,"logicalNot");for(var n=this.readSync(e.dataId),o=new Uint8Array(n.length),a=0;a1||n.rank===1?1:Z(n.shape.slice(1)),f=0;f=0&&a>=0?i:(i+a)%a}))},t.prototype.max=function(e,n){V(e,"max"),nt("max",n,e.rank);for(var o=qe(e.shape,n),a=o[0],i=o[1],s=Ce(a,e.dtype),u=Z(i),c=this.readSync(s.dataId),l=this.readSync(e.dataId),h=0;hd&&(d=m)}c[h]=d}return s},t.prototype.maximum=function(e,n){return V([e,n],"maximum"),this.broadcastedBinaryOp(e,n,e.dtype,(function(o,a){return Math.max(o,a)}))},t.prototype.all=function(e,n){V(e,"all"),nt("all",n,e.rank);for(var o=qe(e.shape,n),a=o[0],i=o[1],s=Ce(a,e.dtype),u=Z(i),c=this.readSync(s.dataId),l=this.readSync(e.dataId),h=0;h0?o[a]=1:o[a]=0;return this.makeOutput(o,e.shape,"float32")},t.prototype.isNaN=function(e){V(e,"x");for(var n=this.readSync(e.dataId),o=new Uint8Array(n.length),a=0;a.5?o[a]=Math.ceil(n[a]):o[a]=i%2==0?i:i+1}return this.makeOutput(o,e.shape,"float32")},t.prototype.exp=function(e){V(e,"exp");for(var n=this.readSync(e.dataId),o=new Float32Array(n.length),a=0;a=0?i:Math.exp(i)-1}return this.makeOutput(n,e.shape,"float32")},t.prototype.eluDer=function(e,n){V([e,n],"eluDer");for(var o=new Float32Array(n.size),a=this.readSync(n.dataId),i=this.readSync(e.dataId),s=0;s=1?i[s]:i[s]*(u+1)}return this.makeOutput(o,n.shape,"float32")},t.prototype.selu=function(e){V(e,"selu");for(var n=Wi,o=zi,a=new Float32Array(e.size),i=this.readSync(e.dataId),s=0;s=0?o*u:n*(Math.exp(u)-1)}return this.makeOutput(a,e.shape,"float32")},t.prototype.clip=function(e,n,o){V(e,"clip");for(var a=new Float32Array(e.size),i=this.readSync(e.dataId),s=0;so?o:u-n,u=a[i]0?1:n}return this.makeOutput(o,e.shape,"float32")},t.prototype.fusedConv2d=function(e){var n=e.input,o=e.filter,a=e.convInfo,i=e.bias,s=e.activation,u=e.preluActivationWeights,c=this.conv2d(n,o,a);return i&&(c=this.add(c,i)),s&&(c=wa(this,c,s,u)),c},t.prototype.conv2d=function(e,n,o){V([e,n],"conv2d");for(var a=o.filterHeight,i=o.filterWidth,s=o.dilationHeight,u=o.dilationWidth,c=o.padInfo.left,l=o.padInfo.top,h=o.dataFormat==="channelsLast",f=re(o.outShape,e.dtype),d=e.strides[0],p=h?e.strides[1]:e.strides[2],m=h?e.strides[2]:1,v=h?1:e.strides[1],g=f.strides[0],x=h?f.strides[1]:f.strides[2],b=h?f.strides[2]:1,y=h?1:f.strides[1],w=this.readSync(e.dataId),_=this.readSync(n.dataId),S=f.values,k=0;k=o.inHeight))for(var U=O*n.strides[0],z=I+B*p,W=0;W=o.inWidth))for(var te=z+ee*m,ie=U+j*n.strides[1],se=0;se=o.inDepth))for(var R=k*n.strides[0],F=b+I*e.strides[1],T=0;T=o.inHeight))for(var z=R+B*n.strides[1],W=F+U*e.strides[2],G=0;G=o.inWidth))for(var ie=z+ee*n.strides[2],se=W+te*o.inChannels,le=ie,pe=0;pe=o.inHeight))for(var k=_*n.strides[0],I=g+S*e.strides[1],R=0;R=o.inWidth))for(var B=k+L*n.strides[1],U=I+O*o.inChannels,z=F,W=B,G=0;Gz?z=te:o==="avg"&&(W+=te,G++)}if(isNaN(z))break}v[T+L*b+S]=o==="avg"?W/G:z}return m.toTensor()},t.prototype.maxPool=function(e,n){return this.pool(e,n,"max")},t.prototype.maxPoolPositions=function(e,n){for(var o=re(n.outShape,"int32"),a=n.strideHeight,i=n.strideWidth,s=n.dilationHeight,u=n.dilationWidth,c=n.effectiveFilterHeight,l=n.effectiveFilterWidth,h=n.padInfo.top,f=n.padInfo.left,d=this.bufferSync(e),p=0;pk&&(k=O,I=F*l+L)}o.set(I,p,v,y,m)}}return o.toTensor()},t.prototype.maxPoolBackprop=function(e,n,o,a){V([n,o],"maxPoolBackprop");for(var i=this.maxPoolPositions(n,a),s=a.strideHeight,u=a.strideWidth,c=a.dilationHeight,l=a.dilationWidth,h=a.effectiveFilterHeight,f=a.effectiveFilterWidth,d=f-1-a.padInfo.left,p=h-1-a.padInfo.top,m=re(n.shape,"float32"),v=this.bufferSync(i),g=this.bufferSync(e),x=0;x=a.outHeight||Math.floor(R)!==R))for(var F=0;F=a.outWidth||Math.floor(T)!==T)){var L=h*f-1-v.get(x,R,T,b)===I*f+F?1:0;L!==0&&(k+=g.get(x,R,T,b)*L)}}}m.set(k,x,y,w,b)}return m.toTensor()},t.prototype.avgPoolBackprop=function(e,n,o){V([e,n],"avgPoolBackprop");for(var a=o.strideHeight,i=o.strideWidth,s=o.filterHeight,u=o.filterWidth,c=o.dilationHeight,l=o.dilationWidth,h=o.effectiveFilterHeight,f=o.effectiveFilterWidth,d=f-1-o.padInfo.left,p=h-1-o.padInfo.top,m=re(n.shape,"float32"),v=1/(s*u),g=this.bufferSync(e),x=0;x=o.outHeight||Math.floor(R)!==R))for(var F=0;F=o.outWidth||Math.floor(T)!==T||(k+=g.get(x,R,T,b))}}m.set(k*v,x,y,w,b)}return m.toTensor()},t.prototype.pool3d=function(e,n,o){V(e,"pool3d");for(var a=n.strideDepth,i=n.strideHeight,s=n.strideWidth,u=n.dilationDepth,c=n.dilationHeight,l=n.dilationWidth,h=n.effectiveFilterDepth,f=n.effectiveFilterHeight,d=n.effectiveFilterWidth,p=n.padInfo.front,m=n.padInfo.top,v=n.padInfo.left,g=o==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=this.readSync(e.dataId),b=re(n.outShape,e.dtype),y=b.values,w=n.outShape[1]*n.outShape[2]*n.outShape[3]*n.outShape[4],_=n.outShape[2]*n.outShape[3]*n.outShape[4],S=n.outShape[3]*n.outShape[4],k=n.outShape[4],I=0;Ihe?he=ke:o==="avg"&&(ve+=ke,Te++),isNaN(he))break}if(isNaN(he))break}if(isNaN(he))break}y[pe+T]=o==="avg"?ve/Te:he}}}return b.toTensor()},t.prototype.avgPool3d=function(e,n){return V(e,"avgPool3d"),this.pool3d(e,n,"avg").toFloat()},t.prototype.avgPool3dBackprop=function(e,n,o){V([e,n],"avgPool3dBackprop");for(var a=o.strideDepth,i=o.strideHeight,s=o.strideWidth,u=o.filterDepth,c=o.filterHeight,l=o.filterWidth,h=o.dilationDepth,f=o.dilationHeight,d=o.dilationWidth,p=o.effectiveFilterDepth,m=o.effectiveFilterHeight,v=o.effectiveFilterWidth,g=p-1-o.padInfo.front,x=v-1-o.padInfo.left,b=m-1-o.padInfo.top,y=re(n.shape,"float32"),w=1/(u*c*l),_=this.bufferSync(e),S=0;S=o.outDepth||Math.floor(z)!==z))for(var W=0;W=o.outHeight||Math.floor(G)!==G))for(var H=0;H=o.outWidth||Math.floor(j)!==j||(B+=_.get(S,z,G,j,k))}}}y.set(B*w,S,I,R,F,k)}return y.toTensor()},t.prototype.maxPool3d=function(e,n){return V(e,"maxPool3d"),this.pool3d(e,n,"max").toFloat()},t.prototype.maxPool3dPositions=function(e,n){for(var o=re(n.outShape,"int32"),a=n.strideDepth,i=n.strideHeight,s=n.strideWidth,u=n.dilationDepth,c=n.dilationHeight,l=n.dilationWidth,h=n.effectiveFilterDepth,f=n.effectiveFilterHeight,d=n.effectiveFilterWidth,p=n.padInfo.front,m=n.padInfo.top,v=n.padInfo.left,g=this.bufferSync(e),x=0;x=U&&(U=ie,z=G*f*d+j*f+te)}o.set(z,x,y,k,T,b)}}}return o.toTensor()},t.prototype.maxPool3dBackprop=function(e,n,o,a){V([n,o],"maxPool3dBackprop");for(var i=this.maxPool3dPositions(n,a),s=a.strideDepth,u=a.strideHeight,c=a.strideWidth,l=a.dilationDepth,h=a.dilationHeight,f=a.dilationWidth,d=a.effectiveFilterDepth,p=a.effectiveFilterHeight,m=a.effectiveFilterWidth,v=d-1-a.padInfo.front,g=m-1-a.padInfo.left,x=p-1-a.padInfo.top,b=re(n.shape,"float32"),y=this.bufferSync(i),w=this.bufferSync(e),_=0;_=a.outDepth||Math.floor(U)!==U))for(var z=0;z=a.outHeight||Math.floor(W)!==W))for(var G=0;G=a.outWidth||Math.floor(H)!==H)){var j=d*p*m-1-y.get(_,U,W,H,S)===B*p*m+z*m+G?1:0;j!==0&&(O+=w.get(_,U,W,H,S)*j)}}}}b.set(O,_,k,I,R,S)}return b.toTensor()},t.prototype.cast=function(e,n){return Ni(e,n,this)},t.prototype.reshape=function(e,n){return Io(e,n)},t.prototype.avgPool=function(e,n){return V(e,"avgPool"),this.pool(e,n,"avg").toFloat()},t.prototype.resizeBilinear=function(e,n,o,a){V(e,"resizeBilinear");for(var i=e.shape,s=i[0],u=i[1],c=i[2],l=i[3],h=this.readSync(e.dataId),f=new Float32Array(Z([s,n,o,l])),d=[a&&n>1?u-1:u,a&&o>1?c-1:c],p=[a&&n>1?n-1:n,a&&o>1?o-1:o],m=0,v=d[0]/p[0],g=d[1]/p[1],x=0;x1?s-1:s,o&&f>1?u-1:u],m=[o&&h>1?h-1:h,o&&f>1?f-1:f],v=p[0]/m[0],g=p[1]/m[1],x=this.readSync(e.dataId),b=0,y=0;y1?u-1:u,a&&o>1?c-1:c],p=[a&&n>1?n-1:n,a&&o>1?o-1:o],m=d[0]/p[0],v=d[1]/p[1],g=0,x=0;x1?s-1:s,o&&f>1?u-1:u],v=[o&&h>1?h-1:h,o&&f>1?f-1:f],g=m[0]/v[0],x=m[1]/v[1],b=1/g,y=1/x,w=2*Math.ceil(b)+2,_=2*Math.ceil(y)+2,S=0;S=h)){var j=k+H*e.strides[1],ee=H*g;if(I===Math.min(s-1,o?Math.round(ee):Math.floor(ee)))for(var te=0;te<_;te++){var ie=te+U;if(!(ie<0||ie>=f)){var se=j+ie*e.strides[2],le=ie*x;L===Math.min(u-1,o?Math.round(le):Math.floor(le))&&(W+=p[se+z])}}}}d[O+z]=W}return Qe(d,n.shape,n.dtype)},t.prototype.batchNormalization=function(e,n,o,a,i,s){V([e,n,o,i,s],"batchNorm");for(var u=this.readSync(e.dataId),c=this.readSync(n.dataId),l=this.readSync(o.dataId),h=i?this.readSync(i.dataId):new Float32Array([1]),f=s?this.readSync(s.dataId):new Float32Array([0]),d=new Float32Array(u.length),p=f.length,m=h.length,v=l.length,g=c.length,x=0,b=0,y=0,w=0,_=0;_=p&&(x=0),b>=g&&(b=0),y>=m&&(y=0),w>=v&&(w=0);return Qe(d,e.shape)},t.prototype.localResponseNormalization4D=function(e,n,o,a,i){V(e,"localResponseNormalization4D");var s=e.shape[3],u=s-1,c=this.readSync(e.dataId),l=e.size,h=new Float32Array(l);function f(v){for(var g=v%s,x=v-g+Math.max(0,g-n),b=v-g+Math.min(g+n,u),y=0;x<=b;x++){var w=c[x];y+=w*w}return y}for(var d=0;d=0&&s[u]1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+n}));for(var a=e.shape[0],i=e.shape[1],s=e.shape[2],u=e.shape[3],c=i*n,l=s*n,h=u/(n*n),f=this.readSync(e.dataId),d=new Float32Array(a*c*l*h),p=0,m=0;m=c))for(var L=p>1?(R-k)*(l-1)/(p-1):0,O=m>1?(F-I)*(h-1)/(m-1):0,B=0;B1?k*(l-1)+B*L:.5*(k+R)*(l-1);if(U<0||U>l-1)for(var z=0;z1?I*(h-1)+z*O:.5*(I+F)*(h-1))<0||fe>h-1)for(W=0;W1?I*(h-1)+z*O:.5*(I+F)*(h-1))<0||fe>h-1)for(W=0;W=e.size/c)throw new Error("Invalid indices: "+m+" does not index into "+e.shape);for(var b=0;b=a/i)throw new Error("Invalid indices: "+g+" does not index into "+o);for(var w=0;w"u"||typeof atob>"u"||typeof btoa>"u");function Su(r){return Ja?Buffer.byteLength(r):new Blob([r]).size}function fs(r){var t=0;r.forEach((function(o){t+=o.byteLength}));var e=new Uint8Array(t),n=0;return r.forEach((function(o){e.set(new Uint8Array(o),n),n+=o.byteLength})),e.buffer}function Au(r){for(r=r.trim();r.endsWith("/");)r=r.slice(0,r.length-1);var t=r.split("/");return t[t.length-1]}function jr(r){if(r.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:r.modelTopology==null?0:Su(JSON.stringify(r.modelTopology)),weightSpecsBytes:r.weightSpecs==null?0:Su(JSON.stringify(r.weightSpecs)),weightDataBytes:r.weightData==null?0:r.weightData.byteLength}}var ht=(function(){function r(){this.saveRouters=[],this.loadRouters=[]}return r.getInstance=function(){return r.instance==null&&(r.instance=new r),r.instance},r.registerSaveRouter=function(t){r.getInstance().saveRouters.push(t)},r.registerLoadRouter=function(t){r.getInstance().loadRouters.push(t)},r.getSaveHandlers=function(t){return r.getHandlers(t,"save")},r.getLoadHandlers=function(t,e){return r.getHandlers(t,"load",e)},r.getHandlers=function(t,e,n){var o=[];return(e==="load"?r.getInstance().loadRouters:r.getInstance().saveRouters).forEach((function(a){var i=a(t,n);i!==null&&o.push(i)})),o},r})(),Kn="://",ln=(function(){function r(){this.managers={}}return r.getInstance=function(){return r.instance==null&&(r.instance=new r),r.instance},r.registerManager=function(t,e){E(t!=null,(function(){return"scheme must not be undefined or null."})),t.endsWith(Kn)&&(t=t.slice(0,t.indexOf(Kn))),E(t.length>0,(function(){return"scheme must not be an empty string."}));var n=r.getInstance();E(n.managers[t]==null,(function(){return"A model store manager is already registered for scheme '"+t+"'."})),n.managers[t]=e},r.getManager=function(t){var e=this.getInstance().managers[t];if(e==null)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},r.getSchemes=function(){return Object.keys(this.getInstance().managers)},r})();function vo(r){if(r.indexOf(Kn)===-1)throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+ln.getSchemes().join(","));return{scheme:r.split(Kn)[0],path:r.split(Kn)[1]}}function Du(r,t,e){return e===void 0&&(e=!1),J(this,void 0,void 0,(function(){var n,o,a,i,s,u,c,l,h;return Q(this,(function(f){switch(f.label){case 0:return E(r!==t,(function(){return"Old path and new path are the same: '"+r+"'"})),E((n=ht.getLoadHandlers(r)).length>0,(function(){return"Copying failed because no load handler is found for source URL "+r+"."})),E(n.length<2,(function(){return"Copying failed because more than one ("+n.length+") load handlers for source URL "+r+"."})),o=n[0],E((a=ht.getSaveHandlers(t)).length>0,(function(){return"Copying failed because no save handler is found for destination URL "+t+"."})),E(a.length<2,(function(){return"Copying failed because more than one ("+n.length+") save handlers for destination URL "+t+"."})),i=a[0],s=vo(r).scheme,u=vo(r).path,c=s===vo(r).scheme,[4,o.load()];case 1:return l=f.sent(),e&&c?[4,ln.getManager(s).removeModel(u)]:[3,3];case 2:f.sent(),f.label=3;case 3:return[4,i.save(l)];case 4:return h=f.sent(),!e||c?[3,6]:[4,ln.getManager(s).removeModel(u)];case 5:f.sent(),f.label=6;case 6:return[2,h.modelArtifactsInfo]}}))}))}var In="models_store",cn="model_info_store";function id(){if(!M().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var r=window||self,t=r.indexedDB||r.mozIndexedDB||r.webkitIndexedDB||r.msIndexedDB||r.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function Qa(r){var t=r.result;t.createObjectStore(In,{keyPath:"modelPath"}),t.createObjectStore(cn,{keyPath:"modelPath"})}var Xn=(function(){function r(t){if(this.indexedDB=id(),t==null||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return r.prototype.save=function(t){return J(this,void 0,void 0,(function(){return Q(this,(function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,t)]}))}))},r.prototype.load=function(){return J(this,void 0,void 0,(function(){return Q(this,(function(t){return[2,this.databaseAction(this.modelPath)]}))}))},r.prototype.databaseAction=function(t,e){var n=this;return new Promise((function(o,a){var i=n.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return Qa(i)},i.onsuccess=function(){var s=i.result;if(e==null){var u=s.transaction(In,"readonly"),c=u.objectStore(In).get(n.modelPath);c.onsuccess=function(){if(c.result==null)return s.close(),a(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));o(c.result.modelArtifacts)},c.onerror=function(m){return s.close(),a(c.error)},u.oncomplete=function(){return s.close()}}else{var l,h=jr(e),f=s.transaction(cn,"readwrite"),d=f.objectStore(cn),p=d.put({modelPath:n.modelPath,modelArtifactsInfo:h});p.onsuccess=function(){var m=(l=s.transaction(In,"readwrite")).objectStore(In).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:h});m.onsuccess=function(){return o({modelArtifactsInfo:h})},m.onerror=function(v){var g=(d=f.objectStore(cn)).delete(n.modelPath);g.onsuccess=function(){return s.close(),a(m.error)},g.onerror=function(x){return s.close(),a(m.error)}}},p.onerror=function(m){return s.close(),a(p.error)},f.oncomplete=function(){l==null?s.close():l.oncomplete=function(){return s.close()}}}},i.onerror=function(s){return a(i.error)}}))},r.URL_SCHEME="indexeddb://",r})(),Tu=function(r){return M().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Xn.URL_SCHEME)?(t=r.slice(Xn.URL_SCHEME.length),new Xn(t)):null;var t};ht.registerSaveRouter(Tu),ht.registerLoadRouter(Tu);var dg=(function(){function r(){this.indexedDB=id()}return r.prototype.listModels=function(){return J(this,void 0,void 0,(function(){var t=this;return Q(this,(function(e){return[2,new Promise((function(n,o){var a=t.indexedDB.open("tensorflowjs",1);a.onupgradeneeded=function(){return Qa(a)},a.onsuccess=function(){var i=a.result,s=i.transaction(cn,"readonly"),u=s.objectStore(cn).getAll();u.onsuccess=function(){for(var c={},l=0,h=u.result;l"u"||window.localStorage===void 0)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,t==null||!t)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=t,this.keys=ud(this.modelPath)}return r.prototype.save=function(t){return J(this,void 0,void 0,(function(){var e,n,o;return Q(this,(function(a){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");e=JSON.stringify(t.modelTopology),n=JSON.stringify(t.weightSpecs),o=jr(t);try{return this.LS.setItem(this.keys.info,JSON.stringify(o)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,(function(i){if(Ja)return Buffer.from(i).toString("base64");for(var s=new Uint8Array(i),u="",c=0,l=s.length;c"u"||window.localStorage!==void 0,(function(){return"Current browser does not appear to support localStorage"})),this.LS=window.localStorage}return r.prototype.listModels=function(){return J(this,void 0,void 0,(function(){var t,e,n,o,a,i;return Q(this,(function(s){for(t={},e=qn+Ht,n=Ht+sd,o=0;o"u")throw new Error("Browser downloads are not supported in this environment since `document` is not present");if(e=window.URL.createObjectURL(new Blob([t.weightData],{type:"application/octet-stream"})),!(t.modelTopology instanceof ArrayBuffer))return[3,1];throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");case 1:return n=[{paths:["./"+this.weightDataFileName],weights:t.weightSpecs}],o={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},a=window.URL.createObjectURL(new Blob([JSON.stringify(o)],{type:"application/json"})),(i=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,i.href=a,[4,Nu((function(){return i.dispatchEvent(new MouseEvent("click"))}))];case 2:return u.sent(),t.weightData==null?[3,4]:((s=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,s.href=e,[4,Nu((function(){return s.dispatchEvent(new MouseEvent("click"))}))]);case 3:u.sent(),u.label=4;case 4:return[2,{modelArtifactsInfo:jr(t)}]}}))}))},r.URL_SCHEME="downloads://",r})(),_g=(function(){function r(t){if(t==null||t.length<1)throw new Error("When calling browserFiles, at least 1 file is required, but received "+t);this.files=t}return r.prototype.load=function(){return J(this,void 0,void 0,(function(){var t,e,n=this;return Q(this,(function(o){return t=this.files[0],e=this.files.slice(1),[2,new Promise((function(a,i){var s=new FileReader;s.onload=function(u){var c=JSON.parse(u.target.result),l=c.modelTopology;if(l!=null){e.length===0&&a({modelTopology:l});var h=c.weightsManifest;if(h!=null){var f;try{f=n.checkManifestAndWeightFiles(h,e)}catch(v){return void i(v)}var d=[],p=[],m=[];h.forEach((function(v){v.paths.forEach((function(g){p.push(g),m.push(null)})),d.push.apply(d,v.weights)})),h.forEach((function(v){v.paths.forEach((function(g){var x=new FileReader;x.onload=function(b){var y=b.target.result,w=p.indexOf(g);m[w]=y,m.indexOf(null)===-1&&a({modelTopology:l,weightSpecs:d,weightData:fs(m),format:c.format,generatedBy:c.generatedBy,convertedBy:c.convertedBy,userDefinedMetadata:c.userDefinedMetadata})},x.onerror=function(b){return i("Failed to weights data from file of path '"+g+"'.")},x.readAsArrayBuffer(f[g])}))}))}else i(new Error("weightManifest field is missing from file "+t.name))}else i(new Error("modelTopology field is missing from file "+t.name))},s.onerror=function(u){return i("Failed to read model topology and weights manifest JSON from file '"+t.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.")},s.readAsText(t)}))]}))}))},r.prototype.checkManifestAndWeightFiles=function(t,e){for(var n=[],o=e.map((function(u){return Au(u.name)})),a={},i=0,s=t;i0,(function(){return"promises must be a none empty array"}))})(r),(function(a,i){E(a>=0&&a<=1,(function(){return"Progress fraction must be in range [0, 1], but got startFraction "+a})),E(i>=0&&i<=1,(function(){return"Progress fraction must be in range [0, 1], but got endFraction "+i})),E(i>=a,(function(){return"startFraction must be no more than endFraction, but got startFraction "+a+" and endFraction "+i}))})(e=e??0,n=n??1);var o=0;return Promise.all(r.map((function(a){return a.then((function(i){var s=e+ ++o/r.length*(n-e);return t(s),i})),a})))}function cd(r,t){return J(this,void 0,void 0,(function(){var e,n,o,a,i,s,u,c,l;return Q(this,(function(h){switch(h.label){case 0:return t==null&&(t={}),e=t.fetchFunc==null?M().platform.fetch:t.fetchFunc,n=r.map((function(f){return e(f,t.requestInit,{isBinary:!0})})),o=0,a=.5,t.onProgress!=null?[3,2]:[4,Promise.all(n)];case 1:return i=h.sent(),[3,4];case 2:return[4,Pu(n,t.onProgress,o,a)];case 3:i=h.sent(),h.label=4;case 4:return s=i.map((function(f){return f.arrayBuffer()})),u=.5,c=1,t.onProgress!=null?[3,6]:[4,Promise.all(s)];case 5:return l=h.sent(),[3,8];case 6:return[4,Pu(s,t.onProgress,u,c)];case 7:l=h.sent(),h.label=8;case 8:return[2,l]}}))}))}function Mu(r){var t=this;return function(e,n,o){return n===void 0&&(n=""),J(t,void 0,void 0,(function(){var a,i,s,u,c,l,h,f,d,p;return Q(this,(function(m){switch(m.label){case 0:if(a=e.map((function(){return!1})),i={},s=o!=null?o.map((function(){return!1})):[],u=[],e.forEach((function(v,g){var x=0;v.weights.forEach((function(b){var y="quantization"in b?b.quantization.dtype:b.dtype,w=$a[y]*Z(b.shape),_=function(){a[g]=!0,i[g]==null&&(i[g]=[]),i[g].push({manifestEntry:b,groupOffset:x,sizeBytes:w})};o!=null?o.forEach((function(S,k){S===b.name&&(_(),s[k]=!0)})):_(),u.push(b.name),x+=w}))})),!s.every((function(v){return v})))throw c=o.filter((function(v,g){return!s[g]})),new Error("Could not find weights in manifest with names: "+c.join(", ")+`. +Manifest JSON has weights with names: `+u.join(", ")+".");return l=a.reduce((function(v,g,x){return g&&v.push(x),v}),[]),h=[],l.forEach((function(v){e[v].paths.forEach((function(g){var x=n+(n.endsWith("/")?"":"/")+g;h.push(x)}))})),[4,r(h)];case 1:return f=m.sent(),d={},p=0,l.forEach((function(v){for(var g=e[v].paths.length,x=0,b=0;b0,(function(){return"URL path for http must not be null, undefined or empty."})),Array.isArray(t)&&E(t.length===2,(function(){return"URL paths for http must have a length of 2, (actual length is "+t.length+")."})),this.path=t,e.requestInit!=null&&e.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return r.prototype.save=function(t){return J(this,void 0,void 0,(function(){var e,n,o,a;return Q(this,(function(i){switch(i.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],o={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(o)],{type:"application/json"}),"model.json"),t.weightData!=null&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((a=i.sent()).ok)return[2,{modelArtifactsInfo:jr(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}}))}))},r.prototype.load=function(){return J(this,void 0,void 0,(function(){var t,e,n,o,a,i,s,u,c,l,h,f;return Q(this,(function(d){switch(d.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=d.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+t.status+". Please verify this URL points to the model JSON of the model to load.");d.label=2;case 2:return d.trys.push([2,4,,5]),[4,t.json()];case 3:return e=d.sent(),[3,5];case 4:throw d.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" 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.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(o=e.modelTopology,a=e.weightsManifest,i=e.generatedBy,s=e.convertedBy,u=e.format,c=e.userDefinedMetadata,o==null&&a==null)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return a==null?[3,7]:[4,this.loadWeights(a)];case 6:f=d.sent(),l=f[0],h=f[1],d.label=7;case 7:return[2,{modelTopology:o,weightSpecs:l,weightData:h,userDefinedMetadata:c,generatedBy:i,convertedBy:s,format:u}]}}))}))},r.prototype.loadWeights=function(t){return J(this,void 0,void 0,(function(){var e,n,o,a,i,s,u,c,l,h,f;return Q(this,(function(d){switch(d.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=(function(p){var m=p.lastIndexOf("/"),v=p.lastIndexOf("?"),g=p.substring(0,m),x=v>m?p.substring(v):"";return[g+"/",x]})(e),o=n[0],a=n[1],i=this.weightPathPrefix||o,s=[],u=0,c=t;u"u"?null:(Array.isArray(r)?r.every((function(e){return Za(e)})):Za(r))?ei(r,{onProgress:t}):null};function ei(r,t){return new ld(r,t)}ht.registerSaveRouter(Ou),ht.registerLoadRouter(Ou);var ka=(function(){function r(t){this.modelArtifacts=t}return r.prototype.load=function(){return J(this,void 0,void 0,(function(){return Q(this,(function(t){return[2,this.modelArtifacts]}))}))},r})(),Eg=(function(){function r(t){this.saveHandler=t}return r.prototype.save=function(t){return J(this,void 0,void 0,(function(){return Q(this,(function(e){return[2,this.saveHandler(t)]}))}))},r})(),ds=Object.freeze({browserFiles:function(r){return new _g(r)},browserHTTPRequest:function(r,t){return ei(r,t)},concatenateArrayBuffers:fs,decodeWeights:ad,encodeWeights:function(r,t){return J(this,void 0,void 0,(function(){var e,n,o,a,i,s=this;return Q(this,(function(u){switch(u.label){case 0:for(e=[],n=[],o=Array.isArray(r)?r.map((function(c){return c.name})):Object.keys(r),a=function(c){var l=o[c],h=Array.isArray(r)?r[c].tensor:r[l];if(h.dtype!=="float32"&&h.dtype!=="int32"&&h.dtype!=="bool"&&h.dtype!=="string")throw new Error("Unsupported dtype in weight '"+l+"': "+h.dtype);var f={name:l,shape:h.shape,dtype:h.dtype};if(h.dtype==="string"){var d=new Promise((function(p){return J(s,void 0,void 0,(function(){var m,v,g,x,b,y,w;return Q(this,(function(_){switch(_.label){case 0:return[4,h.bytes()];case 1:for(m=_.sent(),v=m.reduce((function(S,k){return S+k.length}),0)+ko*m.length,g=new Uint8Array(v),x=0,b=0;b0&&Number.isInteger(e),(function(){return"If provided, numClasses must be a positive integer, but got "+e})),E(n.rank===1,(function(){return"Expected the rank of labels to be 1, but got "+n.rank})),E(o.rank===1,(function(){return"Expected the rank of predictions to be 1, but got "+o.rank})),E(n.shape[0]===o.shape[0],(function(){return"Mismatch in the number of examples: "+n.shape[0]+" vs. "+o.shape[0]+". Labels and predictions should have the same number of elements."})),E(e>0&&Number.isInteger(e),(function(){return"numClasses is required to be a positive integer, but got "+e}));var a=bo(n.asType("int32"),e),i=bo(o.asType("int32"),e);return a.transpose().matMul(i).asType("int32")}}),Rg=Object.freeze({confusionMatrix:Ig}),kg=D({fromPixels_:function(r,t){if(t===void 0&&(t=3),t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(r==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var e=!1,n=!1,o=!1,a=!1,i=!1;if(r.data instanceof Uint8Array)e=!0;else if(typeof ImageData<"u"&&r instanceof ImageData)n=!0;else if(typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement)o=!0;else if(typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement)a=!0;else{if(r.getContext==null)throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was "+r.constructor.name);i=!0}if(o&&o&&r.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the