@naniteninja/dashboard-components-lib 1.0.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/fesm2022/naniteninja-dashboard-components-lib.mjs +181 -191
- package/fesm2022/naniteninja-dashboard-components-lib.mjs.map +1 -1
- package/index.d.ts +1669 -3
- package/package.json +2 -4
- package/src/assets/auto-delegation-modal/cross.svg +17 -17
- package/src/assets/auto-delegation-modal/menu.svg +3 -3
- package/src/assets/auto-delegation-modal/timer-center-dot.svg +25 -25
- package/src/assets/auto-delegation-modal/user-profile.svg +9 -9
- package/src/assets/circle-progress/circle-progress-1.svg +159 -159
- package/src/assets/circle-progress/circle-progress-2.svg +155 -155
- package/src/assets/circle-progress/circle-progress-3.svg +25 -25
- package/src/assets/circle-progress/circle-progress.svg +159 -159
- package/src/assets/client-match-overview/background-eclipse.svg +13 -13
- package/src/assets/grid/icons/filter-button.svg +47 -47
- package/src/assets/grid/images/chips-background-shadow.svg +34 -34
- package/src/assets/icons/back-v2.svg +14 -14
- package/src/assets/icons/checkbox/checkbox-off.svg +72 -72
- package/src/assets/icons/checkbox/checkbox-on.svg +113 -113
- package/src/assets/icons/checkmark-button.svg +72 -72
- package/src/assets/icons/checkmark.svg +7 -7
- package/src/assets/icons/close-icon.svg +3 -3
- package/src/assets/icons/compose-matcher/notes.svg +4 -4
- package/src/assets/icons/compose-matcher/profile.svg +4 -4
- package/src/assets/icons/compose-matcher/suggest.svg +3 -3
- package/src/assets/icons/compose-matcher/visual.svg +3 -3
- package/src/assets/icons/default-profile.svg +23 -23
- package/src/assets/icons/defualt.svg +5 -5
- package/src/assets/icons/first-page.svg +7 -7
- package/src/assets/icons/incrementer/minus.svg +3 -3
- package/src/assets/icons/incrementer/plus.svg +3 -3
- package/src/assets/icons/info.svg +5 -5
- package/src/assets/icons/last-page.svg +7 -7
- package/src/assets/icons/minus.svg +3 -3
- package/src/assets/icons/next-page.svg +6 -6
- package/src/assets/icons/plus.svg +3 -3
- package/src/assets/icons/popup-defualt.svg +34 -34
- package/src/assets/icons/prev-page.svg +6 -6
- package/src/assets/icons/send-icon.svg +4 -4
- package/src/assets/icons/shake.svg +74 -74
- package/src/assets/icons/thumbs-up.svg +28 -28
- package/src/assets/nsfw/blazeface.bundle.js +1 -1
- package/src/assets/nsfw/model/model.json +4085 -4085
- package/src/assets/nsfw/nsfwjs.bundle.js +1 -1
- package/src/assets/nsfw/tf.bundle.js +1 -1
- package/src/assets/scheduler/accept.svg +3 -3
- package/src/assets/scheduler/accept_active.svg +3 -3
- package/src/assets/scheduler/arrow.svg +13 -13
- package/src/assets/scheduler/cancel.svg +3 -3
- package/src/assets/scheduler/cancel_active.svg +3 -3
- package/src/assets/scheduler/heart.svg +18 -18
- package/src/lib/shared-styles/common/animations.scss +48 -48
- package/src/lib/shared-styles/common/base-input-field.scss +132 -132
- package/src/lib/shared-styles/common/buttons.scss +152 -152
- package/src/lib/shared-styles/common/cards.scss +163 -163
- package/src/lib/shared-styles/common/client-dash.scss +5 -5
- package/src/lib/shared-styles/common/date-picker.scss +179 -179
- package/src/lib/shared-styles/common/draggable-scroll-and-marquee.scss +34 -34
- package/src/lib/shared-styles/common/feedback.scss +157 -157
- package/src/lib/shared-styles/common/fonts.scss +3 -3
- package/src/lib/shared-styles/common/information-card.scss +56 -56
- package/src/lib/shared-styles/common/input.scss +110 -110
- package/src/lib/shared-styles/common/lib-styles-utils.scss +157 -157
- package/src/lib/shared-styles/common/lists.scss +91 -91
- package/src/lib/shared-styles/common/login.scss +32 -32
- package/src/lib/shared-styles/common/maps.scss +10 -10
- package/src/lib/shared-styles/common/matcher-dash.scss +49 -49
- package/src/lib/shared-styles/common/modal_styles.scss +32 -32
- package/src/lib/shared-styles/common/notifications-list.scss +9 -9
- package/src/lib/shared-styles/common/overrides.scss +6 -6
- package/src/lib/shared-styles/common/pulse.scss +26 -26
- package/src/lib/shared-styles/common/swiper.scss +5 -5
- package/src/lib/shared-styles/common/tab-menu.scss +74 -74
- package/src/lib/shared-styles/common/theme.scss +55 -55
- package/src/lib/shared-styles/common/typography.scss +121 -121
- package/src/lib/shared-styles/common/user-menu.scss +129 -129
- package/src/lib/shared-styles/fonts/calistoga.font.scss +6 -6
- package/src/lib/shared-styles/fonts/gilroy.font.scss +160 -160
- package/src/lib/shared-styles/styles.scss +25 -25
- package/esm2022/lib/components/auto-delegation/animations.mjs +0 -20
- package/esm2022/lib/components/auto-delegation/auto-delegation-modal.component.mjs +0 -106
- package/esm2022/lib/components/auto-delegation/enums/auto-delegation.event-type.enum.mjs +0 -6
- package/esm2022/lib/components/auto-delegation/enums/auto-delegation.event-value.enum.mjs +0 -7
- package/esm2022/lib/components/auto-delegation/interface/auto-delegation-data.interface.mjs +0 -2
- package/esm2022/lib/components/auto-delegation/interface/auto-delegation.event.interface.mjs +0 -2
- package/esm2022/lib/components/auto-delegation/interface/auto-delegation.modal-data.interface.mjs +0 -2
- package/esm2022/lib/components/auto-delegation/interface/preferences.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/agenda/agenda-day-card/agenda-day-card.component.mjs +0 -37
- package/esm2022/lib/components/calendar/agenda/agenda.component.mjs +0 -98
- package/esm2022/lib/components/calendar/agenda/agenda.module.mjs +0 -24
- package/esm2022/lib/components/calendar/agenda/interfaces/agenda.day.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/agenda/interfaces/agenda.event.inetrface.mjs +0 -2
- package/esm2022/lib/components/calendar/components/edit-recurring-event/edit-recurring-event.component.mjs +0 -40
- package/esm2022/lib/components/calendar/components/event-form/event-form.component.mjs +0 -275
- package/esm2022/lib/components/calendar/components/event-form/event-form.module.mjs +0 -89
- package/esm2022/lib/components/calendar/components/event-info/event-info.component.mjs +0 -40
- package/esm2022/lib/components/calendar/enums/calendar.account.enum.mjs +0 -6
- package/esm2022/lib/components/calendar/enums/calendar.account.icons.enum.mjs +0 -6
- package/esm2022/lib/components/calendar/enums/event-type.enum.mjs +0 -10
- package/esm2022/lib/components/calendar/enums/recurring.edit.options.enum.mjs +0 -7
- package/esm2022/lib/components/calendar/enums/recurring.type.enum.mjs +0 -8
- package/esm2022/lib/components/calendar/interfaces/calendar.account.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/interfaces/calendar.account.theme.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/interfaces/event.form.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/interfaces/event.form.output.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/interfaces/event.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/interfaces/event.time.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/interfaces/recurring.event.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/interfaces/recurring.exception.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/interfaces/recurring.pattern.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/lookups/recurring.options.lookup.mjs +0 -30
- package/esm2022/lib/components/calendar/scheduler/enums/schedule-date-status.enum.mjs +0 -7
- package/esm2022/lib/components/calendar/scheduler/interfaces/scheduler.action.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/scheduler/interfaces/scheduler.event.day.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/scheduler/interfaces/scheduler.event.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/scheduler/interfaces/scheduler.event.suggestion.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/scheduler/interfaces/scheduler.slots.interface.mjs +0 -2
- package/esm2022/lib/components/calendar/scheduler/mock-schedule.mjs +0 -80
- package/esm2022/lib/components/calendar/scheduler/scheduler.component.mjs +0 -144
- package/esm2022/lib/components/calendar/services/calendar-utils.service.mjs +0 -211
- package/esm2022/lib/components/chat/chat.component.mjs +0 -307
- package/esm2022/lib/components/chat/chat.component.module.mjs +0 -85
- package/esm2022/lib/components/chat/chat.service.mjs +0 -63
- package/esm2022/lib/components/chat/enums/sender-types.enum.mjs +0 -6
- package/esm2022/lib/components/chat/gif-selector/gif-selector.component.mjs +0 -77
- package/esm2022/lib/components/chat/gif-selector/gif-selector.service.mjs +0 -41
- package/esm2022/lib/components/chat/gif-selector/tenor-media-format.interface.mjs +0 -2
- package/esm2022/lib/components/chat/gif-selector/tenor-object.interface.mjs +0 -2
- package/esm2022/lib/components/chat/gif-selector/tenor-result.interface.mjs +0 -2
- package/esm2022/lib/components/chat/interfaces/date-messages.interface.mjs +0 -2
- package/esm2022/lib/components/chat/interfaces/message-attachment.interface.mjs +0 -2
- package/esm2022/lib/components/chat/interfaces/message.interface.mjs +0 -2
- package/esm2022/lib/components/chat/interfaces/send-options-message.interface.mjs +0 -2
- package/esm2022/lib/components/chat/interfaces/type-send-message.enum.mjs +0 -7
- package/esm2022/lib/components/chat-suggestion/chat-suggestion.component.mjs +0 -21
- package/esm2022/lib/components/chat-suggestion/interfaces/chat-suggestion.interface.mjs +0 -2
- package/esm2022/lib/components/circle-progress/circle-progress.component.mjs +0 -143
- package/esm2022/lib/components/circle-progress/circle-progress.module.mjs +0 -18
- package/esm2022/lib/components/circle-progress/enums/circle-variable.enum.mjs +0 -6
- package/esm2022/lib/components/circle-progress/interfaces/circle-progress-config.interface.mjs +0 -2
- package/esm2022/lib/components/client-home/client-home.component.mjs +0 -123
- package/esm2022/lib/components/client-home/enums/client-home-component.enum.mjs +0 -9
- package/esm2022/lib/components/client-home/interfaces/chat-meta.interface.mjs +0 -2
- package/esm2022/lib/components/client-home/interfaces/home-dashboard-inputs.interface.mjs +0 -2
- package/esm2022/lib/components/client-home/interfaces/inner-partial-circle-progress-colors.interface.mjs +0 -2
- package/esm2022/lib/components/client-home/interfaces/partial-circle-progress-colors.interface.mjs +0 -2
- package/esm2022/lib/components/client-home/lookup/client-home.config.mjs +0 -30
- package/esm2022/lib/components/client-home/lookup/inner-progress-default-colors.config.mjs +0 -6
- package/esm2022/lib/components/client-home/lookup/inner-progress-pink-colors.config.mjs +0 -6
- package/esm2022/lib/components/client-home/lookup/inner-progress-purple-colors.config.mjs +0 -6
- package/esm2022/lib/components/client-home/lookup/inner-progress-teal-colors.config.mjs +0 -6
- package/esm2022/lib/components/client-home/lookup/inner-progress-white-colors.config.mjs +0 -10
- package/esm2022/lib/components/client-home/lookup/progress-default-colors.config.mjs +0 -10
- package/esm2022/lib/components/client-home/lookup/progress-white-colors.config.mjs +0 -10
- package/esm2022/lib/components/client-home/pipes/chat-meta.pipe.mjs +0 -60
- package/esm2022/lib/components/client-home/pipes/get-color-by-matcher.pipe.mjs +0 -33
- package/esm2022/lib/components/client-match-overview/client-match-overview.component.mjs +0 -300
- package/esm2022/lib/components/client-match-overview/enums/conversation-flag.enum.mjs +0 -6
- package/esm2022/lib/components/client-match-overview/enums/counter-flag-base.enum.mjs +0 -6
- package/esm2022/lib/components/client-match-overview/enums/inner-circle-state.enum.mjs +0 -8
- package/esm2022/lib/components/client-match-overview/interfaces/client-match-overview.interface.mjs +0 -2
- package/esm2022/lib/components/client-match-overview/interfaces/conversation-flag.interface.mjs +0 -2
- package/esm2022/lib/components/client-match-overview/interfaces/dashboard-match-request.interface.mjs +0 -2
- package/esm2022/lib/components/client-match-overview/interfaces/progress-decision.interface.mjs +0 -2
- package/esm2022/lib/components/client-match-overview/interfaces/progress-facts.interface.mjs +0 -2
- package/esm2022/lib/components/client-match-overview/lookups/computer-inner-state.lookup.mjs +0 -81
- package/esm2022/lib/components/client-match-overview/lookups/limit-dates-indicator.lookup.mjs +0 -8
- package/esm2022/lib/components/client-match-overview/progress-ticker/progress-gap.config.mjs +0 -4
- package/esm2022/lib/components/client-match-overview/progress-ticker/progress-ticker.config.mjs +0 -3
- package/esm2022/lib/components/client-match-overview/progress-ticker/progress-ticker.service.mjs +0 -43
- package/esm2022/lib/components/dashboard-swipeable-tabs/dashboard-swipeable-tabs.component.mjs +0 -113
- package/esm2022/lib/components/dashboard-swipeable-tabs/lookups/dashboard-main-swiper-options.mjs +0 -11
- package/esm2022/lib/components/dashboard-swipeable-tabs/lookups/dashboard-thumbs-swiper-options.mjs +0 -27
- package/esm2022/lib/components/dashboard-swipeable-tabs/lookups/main-swiper-default-options.mjs +0 -19
- package/esm2022/lib/components/dashboard-swipeable-tabs/lookups/thumbs-swiper-default-options.mjs +0 -21
- package/esm2022/lib/components/lib-client-dashboard/client-dashboard.component.mjs +0 -170
- package/esm2022/lib/components/lib-client-dashboard/enums/alert-status-fields.enum.mjs +0 -11
- package/esm2022/lib/components/lib-client-dashboard/enums/client-dashboard-component.enum.mjs +0 -7
- package/esm2022/lib/components/lib-client-dashboard/interfaces/client-dashboard-inputs.interface.mjs +0 -2
- package/esm2022/lib/components/lib-client-dashboard/lookups/client-dashboard.config.mjs +0 -15
- package/esm2022/lib/components/lib-compose-matcher-dash/compose-matcher-dash.component.mjs +0 -146
- package/esm2022/lib/components/lib-compose-matcher-dash/interfaces/chart-data.interface.mjs +0 -2
- package/esm2022/lib/components/lib-compose-matcher-dash/interfaces/chat-identifier.interface.mjs +0 -2
- package/esm2022/lib/components/lib-compose-matcher-dash/interfaces/matcher-dashboard-inputs.interface.mjs +0 -2
- package/esm2022/lib/components/lib-compose-matcher-dash/interfaces/matcher-profile.interface.mjs +0 -2
- package/esm2022/lib/components/lib-compose-matcher-dash/interfaces/prospect-data.interface.mjs +0 -2
- package/esm2022/lib/components/lib-compose-matcher-dash/pipes/get-profile-with-progress.pipe.mjs +0 -21
- package/esm2022/lib/components/matcher-statuses/enums/matcher-statuses.enum.mjs +0 -15
- package/esm2022/lib/components/matcher-statuses/interfaces/status.interface.mjs +0 -2
- package/esm2022/lib/components/matcher-statuses/lookups/matcher-statuses.lookup.mjs +0 -54
- package/esm2022/lib/components/matcher-statuses/matcher-statuses.component.mjs +0 -58
- package/esm2022/lib/components/matcher-statuses/pipes/is-status-included.pipe.mjs +0 -19
- package/esm2022/lib/components/profile-card/profile-card.component.mjs +0 -35
- package/esm2022/lib/components/profile-card/profile-card.module.mjs +0 -19
- package/esm2022/lib/components/spider-chart/interfaces/chart-data-circle.interface.mjs +0 -2
- package/esm2022/lib/components/spider-chart/interfaces/chart-data-defs-f.interface.mjs +0 -2
- package/esm2022/lib/components/spider-chart/interfaces/chart-data-defs-lg.interface.mjs +0 -2
- package/esm2022/lib/components/spider-chart/interfaces/chart-data-defs-rg.interface.mjs +0 -2
- package/esm2022/lib/components/spider-chart/interfaces/config.interface.mjs +0 -2
- package/esm2022/lib/components/spider-chart/interfaces/dataset.interface.mjs +0 -2
- package/esm2022/lib/components/spider-chart/interfaces/polygon-color.interface.mjs +0 -2
- package/esm2022/lib/components/spider-chart/interfaces/spider-chart-attribute.interface.mjs +0 -2
- package/esm2022/lib/components/spider-chart/lookup/default-spider-config.lookup.mjs +0 -18
- package/esm2022/lib/components/spider-chart/lookup/default-spider-config.mjs +0 -67
- package/esm2022/lib/components/spider-chart/lookup/demo-polygon-colors.lookup.mjs +0 -11
- package/esm2022/lib/components/spider-chart/lookup/svg-config.lookup.mjs +0 -277
- package/esm2022/lib/components/spider-chart/spider-chart.component.mjs +0 -235
- package/esm2022/lib/enums/direction.enum.mjs +0 -6
- package/esm2022/lib/enums/form-field-type.mjs +0 -30
- package/esm2022/lib/enums/local-storage-keys.enum.mjs +0 -5
- package/esm2022/lib/enums/status-types.mjs +0 -8
- package/esm2022/lib/model/select-option-template.mjs +0 -2
- package/esm2022/lib/operations/operations.mjs +0 -19
- package/esm2022/lib/pipes/array-sort/array.sort.pipe.mjs +0 -49
- package/esm2022/lib/pipes/count-non-empty-fields/count-non-empty-fields.pipe.mjs +0 -17
- package/esm2022/lib/pipes/date-localization/date-localization.pipe.mjs +0 -31
- package/esm2022/lib/pipes/fallback-translate/fallback-translate.pipe.mjs +0 -28
- package/esm2022/lib/pipes/get-display-value/get-display-value.pipe.mjs +0 -59
- package/esm2022/lib/pipes/get-multi-select-display-text/get-multi-select-display-text.pipe.mjs +0 -22
- package/esm2022/lib/pipes/initials/initials.pipe.mjs +0 -25
- package/esm2022/lib/pipes/round/round.pipe.mjs +0 -17
- package/esm2022/lib/pipes/update-llm-preference/update-llm-preference.pipe.mjs +0 -25
- package/esm2022/lib/services/abstract-cache.service.mjs +0 -10
- package/esm2022/lib/shared/shared/alert-popup/alert-popup.component.mjs +0 -38
- package/esm2022/lib/shared/shared/message-modal/message-modal.component.mjs +0 -95
- package/esm2022/lib/shared/shared/status-icon/status-icon.component.mjs +0 -14
- package/esm2022/lib/shared/shared.module.mjs +0 -23
- package/esm2022/naniteninja-dashboard-components-lib.mjs +0 -5
- package/esm2022/public-api.mjs +0 -122
- package/lib/components/auto-delegation/animations.d.ts +0 -1
- package/lib/components/auto-delegation/auto-delegation-modal.component.d.ts +0 -29
- package/lib/components/auto-delegation/enums/auto-delegation.event-type.enum.d.ts +0 -4
- package/lib/components/auto-delegation/enums/auto-delegation.event-value.enum.d.ts +0 -5
- package/lib/components/auto-delegation/interface/auto-delegation-data.interface.d.ts +0 -31
- package/lib/components/auto-delegation/interface/auto-delegation.event.interface.d.ts +0 -6
- package/lib/components/auto-delegation/interface/auto-delegation.modal-data.interface.d.ts +0 -8
- package/lib/components/auto-delegation/interface/preferences.interface.d.ts +0 -17
- package/lib/components/calendar/agenda/agenda-day-card/agenda-day-card.component.d.ts +0 -12
- package/lib/components/calendar/agenda/agenda.component.d.ts +0 -22
- package/lib/components/calendar/agenda/agenda.module.d.ts +0 -12
- package/lib/components/calendar/agenda/interfaces/agenda.day.interface.d.ts +0 -7
- package/lib/components/calendar/agenda/interfaces/agenda.event.inetrface.d.ts +0 -9
- package/lib/components/calendar/components/edit-recurring-event/edit-recurring-event.component.d.ts +0 -19
- package/lib/components/calendar/components/event-form/event-form.component.d.ts +0 -67
- package/lib/components/calendar/components/event-form/event-form.module.d.ts +0 -20
- package/lib/components/calendar/components/event-info/event-info.component.d.ts +0 -24
- package/lib/components/calendar/enums/calendar.account.enum.d.ts +0 -4
- package/lib/components/calendar/enums/calendar.account.icons.enum.d.ts +0 -4
- package/lib/components/calendar/enums/event-type.enum.d.ts +0 -8
- package/lib/components/calendar/enums/recurring.edit.options.enum.d.ts +0 -5
- package/lib/components/calendar/enums/recurring.type.enum.d.ts +0 -6
- package/lib/components/calendar/interfaces/calendar.account.interface.d.ts +0 -14
- package/lib/components/calendar/interfaces/calendar.account.theme.interface.d.ts +0 -5
- package/lib/components/calendar/interfaces/event.form.interface.d.ts +0 -22
- package/lib/components/calendar/interfaces/event.form.output.interface.d.ts +0 -10
- package/lib/components/calendar/interfaces/event.interface.d.ts +0 -33
- package/lib/components/calendar/interfaces/event.time.interface.d.ts +0 -4
- package/lib/components/calendar/interfaces/recurring.event.interface.d.ts +0 -16
- package/lib/components/calendar/interfaces/recurring.exception.interface.d.ts +0 -14
- package/lib/components/calendar/interfaces/recurring.pattern.interface.d.ts +0 -16
- package/lib/components/calendar/lookups/recurring.options.lookup.d.ts +0 -2
- package/lib/components/calendar/scheduler/enums/schedule-date-status.enum.d.ts +0 -5
- package/lib/components/calendar/scheduler/interfaces/scheduler.action.interface.d.ts +0 -10
- package/lib/components/calendar/scheduler/interfaces/scheduler.event.day.interface.d.ts +0 -5
- package/lib/components/calendar/scheduler/interfaces/scheduler.event.interface.d.ts +0 -26
- package/lib/components/calendar/scheduler/interfaces/scheduler.event.suggestion.interface.d.ts +0 -13
- package/lib/components/calendar/scheduler/interfaces/scheduler.slots.interface.d.ts +0 -6
- package/lib/components/calendar/scheduler/mock-schedule.d.ts +0 -9
- package/lib/components/calendar/scheduler/scheduler.component.d.ts +0 -36
- package/lib/components/calendar/services/calendar-utils.service.d.ts +0 -39
- package/lib/components/chat/chat.component.d.ts +0 -70
- package/lib/components/chat/chat.component.module.d.ts +0 -22
- package/lib/components/chat/chat.service.d.ts +0 -15
- package/lib/components/chat/enums/sender-types.enum.d.ts +0 -4
- package/lib/components/chat/gif-selector/gif-selector.component.d.ts +0 -25
- package/lib/components/chat/gif-selector/gif-selector.service.d.ts +0 -15
- package/lib/components/chat/gif-selector/tenor-media-format.interface.d.ts +0 -7
- package/lib/components/chat/gif-selector/tenor-object.interface.d.ts +0 -5
- package/lib/components/chat/gif-selector/tenor-result.interface.d.ts +0 -16
- package/lib/components/chat/interfaces/date-messages.interface.d.ts +0 -6
- package/lib/components/chat/interfaces/message-attachment.interface.d.ts +0 -6
- package/lib/components/chat/interfaces/message.interface.d.ts +0 -11
- package/lib/components/chat/interfaces/send-options-message.interface.d.ts +0 -5
- package/lib/components/chat/interfaces/type-send-message.enum.d.ts +0 -5
- package/lib/components/chat-suggestion/chat-suggestion.component.d.ts +0 -9
- package/lib/components/chat-suggestion/interfaces/chat-suggestion.interface.d.ts +0 -4
- package/lib/components/circle-progress/circle-progress.component.d.ts +0 -31
- package/lib/components/circle-progress/circle-progress.module.d.ts +0 -8
- package/lib/components/circle-progress/enums/circle-variable.enum.d.ts +0 -4
- package/lib/components/circle-progress/interfaces/circle-progress-config.interface.d.ts +0 -29
- package/lib/components/client-home/client-home.component.d.ts +0 -44
- package/lib/components/client-home/enums/client-home-component.enum.d.ts +0 -7
- package/lib/components/client-home/interfaces/chat-meta.interface.d.ts +0 -7
- package/lib/components/client-home/interfaces/home-dashboard-inputs.interface.d.ts +0 -45
- package/lib/components/client-home/interfaces/inner-partial-circle-progress-colors.interface.d.ts +0 -5
- package/lib/components/client-home/interfaces/partial-circle-progress-colors.interface.d.ts +0 -9
- package/lib/components/client-home/lookup/client-home.config.d.ts +0 -2
- package/lib/components/client-home/lookup/inner-progress-default-colors.config.d.ts +0 -2
- package/lib/components/client-home/lookup/inner-progress-pink-colors.config.d.ts +0 -2
- package/lib/components/client-home/lookup/inner-progress-purple-colors.config.d.ts +0 -2
- package/lib/components/client-home/lookup/inner-progress-teal-colors.config.d.ts +0 -2
- package/lib/components/client-home/lookup/inner-progress-white-colors.config.d.ts +0 -2
- package/lib/components/client-home/lookup/progress-default-colors.config.d.ts +0 -2
- package/lib/components/client-home/lookup/progress-white-colors.config.d.ts +0 -2
- package/lib/components/client-home/pipes/chat-meta.pipe.d.ts +0 -10
- package/lib/components/client-home/pipes/get-color-by-matcher.pipe.d.ts +0 -10
- package/lib/components/client-match-overview/client-match-overview.component.d.ts +0 -55
- package/lib/components/client-match-overview/enums/conversation-flag.enum.d.ts +0 -4
- package/lib/components/client-match-overview/enums/counter-flag-base.enum.d.ts +0 -4
- package/lib/components/client-match-overview/enums/inner-circle-state.enum.d.ts +0 -6
- package/lib/components/client-match-overview/interfaces/client-match-overview.interface.d.ts +0 -19
- package/lib/components/client-match-overview/interfaces/conversation-flag.interface.d.ts +0 -8
- package/lib/components/client-match-overview/interfaces/dashboard-match-request.interface.d.ts +0 -7
- package/lib/components/client-match-overview/interfaces/progress-decision.interface.d.ts +0 -10
- package/lib/components/client-match-overview/interfaces/progress-facts.interface.d.ts +0 -11
- package/lib/components/client-match-overview/lookups/computer-inner-state.lookup.d.ts +0 -7
- package/lib/components/client-match-overview/lookups/limit-dates-indicator.lookup.d.ts +0 -5
- package/lib/components/client-match-overview/progress-ticker/progress-gap.config.d.ts +0 -2
- package/lib/components/client-match-overview/progress-ticker/progress-ticker.config.d.ts +0 -2
- package/lib/components/client-match-overview/progress-ticker/progress-ticker.service.d.ts +0 -11
- package/lib/components/dashboard-swipeable-tabs/dashboard-swipeable-tabs.component.d.ts +0 -29
- package/lib/components/dashboard-swipeable-tabs/lookups/dashboard-main-swiper-options.d.ts +0 -2
- package/lib/components/dashboard-swipeable-tabs/lookups/dashboard-thumbs-swiper-options.d.ts +0 -2
- package/lib/components/dashboard-swipeable-tabs/lookups/main-swiper-default-options.d.ts +0 -2
- package/lib/components/dashboard-swipeable-tabs/lookups/thumbs-swiper-default-options.d.ts +0 -2
- package/lib/components/lib-client-dashboard/client-dashboard.component.d.ts +0 -73
- package/lib/components/lib-client-dashboard/enums/alert-status-fields.enum.d.ts +0 -9
- package/lib/components/lib-client-dashboard/enums/client-dashboard-component.enum.d.ts +0 -5
- package/lib/components/lib-client-dashboard/interfaces/client-dashboard-inputs.interface.d.ts +0 -29
- package/lib/components/lib-client-dashboard/lookups/client-dashboard.config.d.ts +0 -2
- package/lib/components/lib-compose-matcher-dash/compose-matcher-dash.component.d.ts +0 -48
- package/lib/components/lib-compose-matcher-dash/interfaces/chart-data.interface.d.ts +0 -5
- package/lib/components/lib-compose-matcher-dash/interfaces/chat-identifier.interface.d.ts +0 -5
- package/lib/components/lib-compose-matcher-dash/interfaces/matcher-dashboard-inputs.interface.d.ts +0 -26
- package/lib/components/lib-compose-matcher-dash/interfaces/matcher-profile.interface.d.ts +0 -8
- package/lib/components/lib-compose-matcher-dash/interfaces/prospect-data.interface.d.ts +0 -24
- package/lib/components/lib-compose-matcher-dash/pipes/get-profile-with-progress.pipe.d.ts +0 -9
- package/lib/components/matcher-statuses/enums/matcher-statuses.enum.d.ts +0 -13
- package/lib/components/matcher-statuses/interfaces/status.interface.d.ts +0 -6
- package/lib/components/matcher-statuses/lookups/matcher-statuses.lookup.d.ts +0 -2
- package/lib/components/matcher-statuses/matcher-statuses.component.d.ts +0 -23
- package/lib/components/matcher-statuses/pipes/is-status-included.pipe.d.ts +0 -8
- package/lib/components/profile-card/profile-card.component.d.ts +0 -11
- package/lib/components/profile-card/profile-card.module.d.ts +0 -9
- package/lib/components/spider-chart/interfaces/chart-data-circle.interface.d.ts +0 -10
- package/lib/components/spider-chart/interfaces/chart-data-defs-f.interface.d.ts +0 -11
- package/lib/components/spider-chart/interfaces/chart-data-defs-lg.interface.d.ts +0 -11
- package/lib/components/spider-chart/interfaces/chart-data-defs-rg.interface.d.ts +0 -10
- package/lib/components/spider-chart/interfaces/config.interface.d.ts +0 -19
- package/lib/components/spider-chart/interfaces/dataset.interface.d.ts +0 -7
- package/lib/components/spider-chart/interfaces/polygon-color.interface.d.ts +0 -4
- package/lib/components/spider-chart/interfaces/spider-chart-attribute.interface.d.ts +0 -6
- package/lib/components/spider-chart/lookup/default-spider-config.d.ts +0 -2
- package/lib/components/spider-chart/lookup/default-spider-config.lookup.d.ts +0 -2
- package/lib/components/spider-chart/lookup/demo-polygon-colors.lookup.d.ts +0 -2
- package/lib/components/spider-chart/lookup/svg-config.lookup.d.ts +0 -8
- package/lib/components/spider-chart/spider-chart.component.d.ts +0 -52
- package/lib/enums/direction.enum.d.ts +0 -4
- package/lib/enums/form-field-type.d.ts +0 -28
- package/lib/enums/local-storage-keys.enum.d.ts +0 -3
- package/lib/enums/status-types.d.ts +0 -6
- package/lib/model/select-option-template.d.ts +0 -5
- package/lib/operations/operations.d.ts +0 -19
- package/lib/pipes/array-sort/array.sort.pipe.d.ts +0 -7
- package/lib/pipes/count-non-empty-fields/count-non-empty-fields.pipe.d.ts +0 -7
- package/lib/pipes/date-localization/date-localization.pipe.d.ts +0 -8
- package/lib/pipes/fallback-translate/fallback-translate.pipe.d.ts +0 -11
- package/lib/pipes/get-display-value/get-display-value.pipe.d.ts +0 -13
- package/lib/pipes/get-multi-select-display-text/get-multi-select-display-text.pipe.d.ts +0 -8
- package/lib/pipes/initials/initials.pipe.d.ts +0 -7
- package/lib/pipes/round/round.pipe.d.ts +0 -7
- package/lib/pipes/update-llm-preference/update-llm-preference.pipe.d.ts +0 -8
- package/lib/services/abstract-cache.service.d.ts +0 -9
- package/lib/shared/shared/alert-popup/alert-popup.component.d.ts +0 -14
- package/lib/shared/shared/message-modal/message-modal.component.d.ts +0 -29
- package/lib/shared/shared/status-icon/status-icon.component.d.ts +0 -7
- package/lib/shared/shared.module.d.ts +0 -13
- package/naniteninja-dashboard-components-lib-1.0.0.tgz +0 -0
- package/public-api.d.ts +0 -121
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! For license information please see nsfwjs.bundle.js.LICENSE.txt */
|
|
1
|
+
/*! For license information please see nsfwjs.bundle.js.LICENSE.txt */
|
|
2
2
|
var nsfwjs;(()=>{var e={99951:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Abs:()=>nt,Acos:()=>rt,Acosh:()=>st,AdadeltaOptimizer:()=>lu,AdagradOptimizer:()=>hu,AdamOptimizer:()=>fu,AdamaxOptimizer:()=>wu,Add:()=>at,AddN:()=>it,All:()=>ot,Any:()=>ut,ArgMax:()=>lt,ArgMin:()=>ct,Asin:()=>ht,Asinh:()=>pt,Atan:()=>dt,Atan2:()=>mt,Atanh:()=>ft,AvgPool:()=>gt,AvgPool3D:()=>bt,AvgPool3DGrad:()=>xt,AvgPoolGrad:()=>yt,BatchMatMul:()=>wt,BatchToSpaceND:()=>vt,Bincount:()=>kt,BitwiseAnd:()=>It,BroadcastArgs:()=>St,BroadcastTo:()=>Nt,Callback:()=>RS,CallbackList:()=>pw,Cast:()=>Tt,Ceil:()=>Ct,ClipByValue:()=>$t,Complex:()=>Et,ComplexAbs:()=>At,Concat:()=>Rt,Conv2D:()=>Ot,Conv2DBackpropFilter:()=>Ft,Conv2DBackpropInput:()=>_t,Conv3D:()=>Dt,Conv3DBackpropFilterV2:()=>Mt,Conv3DBackpropInputV2:()=>Lt,Cos:()=>zt,Cosh:()=>Pt,CropAndResize:()=>Ut,Cumprod:()=>Bt,Cumsum:()=>Wt,CustomCallback:()=>mw,DataStorage:()=>X,DenseBincount:()=>Vt,DepthToSpace:()=>Gt,DepthwiseConv2dNative:()=>jt,DepthwiseConv2dNativeBackpropFilter:()=>Ht,DepthwiseConv2dNativeBackpropInput:()=>qt,Diag:()=>Kt,Dilation2D:()=>Xt,Dilation2DBackpropFilter:()=>Jt,Dilation2DBackpropInput:()=>Yt,Draw:()=>Zt,ENV:()=>Je,EarlyStopping:()=>_S,Einsum:()=>en,Elu:()=>tn,EluGrad:()=>nn,Environment:()=>Ke,Equal:()=>sn,Erf:()=>rn,Exp:()=>an,ExpandDims:()=>on,Expm1:()=>un,FFT:()=>ln,Fill:()=>cn,FlipLeftRight:()=>hn,Floor:()=>pn,FloorDiv:()=>dn,FromPixels:()=>gs,FusedBatchNorm:()=>fn,FusedConv2D:()=>xs,FusedDepthwiseConv2D:()=>ws,GPGPUContext:()=>iL,GatherNd:()=>gn,GatherV2:()=>mn,GraphModel:()=>sC,Greater:()=>yn,GreaterEqual:()=>bn,History:()=>fw,IFFT:()=>wn,Identity:()=>xn,Imag:()=>vn,InputSpec:()=>yx,IsFinite:()=>kn,IsInf:()=>In,IsNan:()=>Nn,KernelBackend:()=>Y,LRN:()=>Ln,LRNGrad:()=>zn,LayerVariable:()=>dx,LayersModel:()=>bv,LeakyRelu:()=>Sn,Less:()=>Tn,LessEqual:()=>Cn,LinSpace:()=>$n,Log:()=>En,Log1p:()=>An,LogSoftmax:()=>Dn,LogicalAnd:()=>Rn,LogicalNot:()=>On,LogicalOr:()=>Fn,LogicalXor:()=>_n,LowerBound:()=>Mn,MathBackendCPU:()=>x$,MathBackendWebGL:()=>Rz,MatrixBandPart:()=>Pn,Max:()=>Bn,MaxPool:()=>Un,MaxPool3D:()=>Gn,MaxPool3DGrad:()=>jn,MaxPoolGrad:()=>Vn,MaxPoolWithArgmax:()=>Hn,Maximum:()=>Wn,Mean:()=>qn,Min:()=>Kn,Minimum:()=>Xn,MirrorPad:()=>Yn,Mod:()=>Jn,MomentumOptimizer:()=>ku,Multinomial:()=>Zn,Multiply:()=>Qn,Neg:()=>er,NonMaxSuppressionV3:()=>nr,NonMaxSuppressionV4:()=>rr,NonMaxSuppressionV5:()=>sr,NotEqual:()=>tr,OP_SCOPE_SUFFIX:()=>si,OneHot:()=>ir,OnesLike:()=>ar,Optimizer:()=>uu,OptimizerConstructors:()=>ql,Pack:()=>or,PadV2:()=>ur,Pool:()=>lr,Pow:()=>cr,Prelu:()=>hr,Prod:()=>pr,RMSPropOptimizer:()=>Iu,RNN:()=>$k,RaggedGather:()=>dr,RaggedRange:()=>fr,RaggedTensorToTensor:()=>mr,Range:()=>gr,Rank:()=>Ia,Real:()=>yr,RealDiv:()=>Qt,Reciprocal:()=>br,Reduction:()=>Of,Relu:()=>xr,Relu6:()=>Sr,Reshape:()=>wr,ResizeBilinear:()=>Ir,ResizeBilinearGrad:()=>Nr,ResizeNearestNeighbor:()=>vr,ResizeNearestNeighborGrad:()=>kr,Reverse:()=>Tr,RotateWithOffset:()=>ys,Round:()=>Cr,Rsqrt:()=>$r,SGDOptimizer:()=>vu,ScatterNd:()=>Er,SearchSorted:()=>Rr,Select:()=>Or,Selu:()=>Fr,Sequential:()=>Iv,Sigmoid:()=>zr,Sign:()=>Lr,Sin:()=>Dr,Sinh:()=>Mr,Slice:()=>_r,Softmax:()=>Gr,Softplus:()=>Pr,SpaceToBatchND:()=>Ur,SparseFillEmptyRows:()=>jr,SparseReshape:()=>Hr,SparseSegmentMean:()=>qr,SparseSegmentSum:()=>Kr,SparseToDense:()=>Xr,SplitV:()=>Vr,Sqrt:()=>Br,Square:()=>Jr,SquaredDifference:()=>Yr,StaticRegexReplace:()=>Zr,Step:()=>ms,StridedSlice:()=>Qr,StringNGrams:()=>es,StringSplit:()=>ts,StringToHashBucketFast:()=>ns,Sub:()=>rs,Sum:()=>Wr,SymbolicTensor:()=>bx,Tan:()=>ss,Tanh:()=>as,Tensor:()=>wa,TensorBuffer:()=>ga,TensorScatterUpdate:()=>Ar,Tile:()=>is,TopK:()=>os,Transform:()=>us,Transpose:()=>ls,Unique:()=>cs,Unpack:()=>hs,UnsortedSegmentSum:()=>ps,UpperBound:()=>ds,Variable:()=>ka,ZerosLike:()=>fs,_FusedMatMul:()=>bs,abs:()=>mu,acos:()=>Kl,acosh:()=>Xl,add:()=>Wo,addN:()=>Yl,all:()=>Jl,any:()=>Zl,argMax:()=>Ql,argMin:()=>ec,asin:()=>tc,asinh:()=>nc,atan:()=>rc,atan2:()=>sc,atanh:()=>ac,avgPool:()=>kc,avgPool3d:()=>Ic,backend:()=>Ri,backend_util:()=>y,basicLSTMCell:()=>$c,batchNorm:()=>Ac,batchNorm2d:()=>Rc,batchNorm3d:()=>Oc,batchNorm4d:()=>Fc,batchToSpaceND:()=>Ec,bincount:()=>_c,bitwiseAnd:()=>Dc,booleanMaskAsync:()=>Md,broadcastArgs:()=>Mc,broadcastTo:()=>Lc,broadcast_util:()=>o,browser:()=>c,buffer:()=>Mo,callbacks:()=>DS,cast:()=>Lo,ceil:()=>zc,clipByValue:()=>Pc,clone:()=>zo,complex:()=>ii,concat:()=>Nc,concat1d:()=>Bc,concat2d:()=>Wc,concat3d:()=>Uc,concat4d:()=>Vc,constraints:()=>x,conv1d:()=>jc,conv2d:()=>Gc,conv2dTranspose:()=>qc,conv3d:()=>Kc,conv3dTranspose:()=>Yc,copyRegisteredKernels:()=>Fs,cos:()=>Jc,cosh:()=>Zc,cosineWindow:()=>Vd,cumprod:()=>Qc,cumsum:()=>eh,customGrad:()=>Qo,data:()=>j,denseBincount:()=>th,deprecationWarn:()=>mi,depthToSpace:()=>nh,depthwiseConv2d:()=>rh,deregisterOp:()=>US,device_util:()=>a,diag:()=>sh,dilation2d:()=>ah,disableDeprecationWarnings:()=>fi,dispose:()=>vi,disposeVariables:()=>gi,div:()=>Vo,divNoNan:()=>uh,dot:()=>lh,dropout:()=>Wd,einsum:()=>ch,elu:()=>hh,enableDebugMode:()=>di,enableProdMode:()=>pi,enclosingPowerOfTwo:()=>Ud,engine:()=>yi,ensureShape:()=>ph,env:()=>Ye,equal:()=>ih,erf:()=>dh,euclideanNorm:()=>Ch,exp:()=>$h,expandDims:()=>Eh,expm1:()=>Ah,eye:()=>Oh,fft:()=>cd,fill:()=>cu,findBackend:()=>$i,findBackendFactory:()=>Ei,floor:()=>Fh,floorDiv:()=>Uo,forceHalfFloat:()=>Fz,fused:()=>m,gather:()=>_h,gatherND:()=>Bd,gather_util:()=>h,getBackend:()=>Ti,getGradient:()=>Cs,getKernel:()=>Ts,getKernelsForBackend:()=>$s,gpgpu_util:()=>K,grad:()=>Ko,grads:()=>Xo,greater:()=>Dh,greaterEqual:()=>Mh,ifft:()=>hd,imag:()=>Ku,image:()=>Zf,inTopKAsync:()=>Gd,initializers:()=>w,input:()=>Tv,io:()=>u,irfft:()=>pd,isFinite:()=>Lh,isInf:()=>zh,isNaN:()=>Ph,keep:()=>ki,kernel_impls:()=>b,layers:()=>v,leakyRelu:()=>Bh,less:()=>Wh,lessEqual:()=>Uh,linalg:()=>Qf,linspace:()=>Vh,loadGraphModel:()=>aC,loadGraphModelSync:()=>iC,loadLayersModel:()=>kv,localResponseNormalization:()=>Gh,log:()=>jh,log1p:()=>Hh,logSigmoid:()=>Kh,logSoftmax:()=>Xh,logSumExp:()=>Yh,logicalAnd:()=>Jh,logicalNot:()=>Zh,logicalOr:()=>Qh,logicalXor:()=>ep,losses:()=>em,lowerBound:()=>rp,matMul:()=>Hu,math:()=>l,max:()=>kh,maxPool:()=>sp,maxPool3d:()=>ap,maxPoolWithArgmax:()=>ip,maximum:()=>xu,mean:()=>op,memory:()=>bi,meshgrid:()=>cp,metrics:()=>k,min:()=>Ih,minimum:()=>hp,mirrorPad:()=>pp,mod:()=>dp,model:()=>Nv,models:()=>I,moments:()=>fp,movingAverage:()=>Ld,mul:()=>Go,multiRNNCell:()=>mp,multinomial:()=>gp,neg:()=>Xu,nextFrame:()=>am,norm:()=>Th,notEqual:()=>yp,oneHot:()=>qu,ones:()=>lp,onesLike:()=>bp,op:()=>ai,outerProduct:()=>xp,pad:()=>wp,pad1d:()=>vp,pad2d:()=>kp,pad3d:()=>Ip,pad4d:()=>Np,pool:()=>Tp,pow:()=>pu,prelu:()=>Cp,print:()=>Bo,prod:()=>$p,profile:()=>xi,raggedGather:()=>Ep,raggedRange:()=>Ap,raggedTensorToTensor:()=>Rp,rand:()=>Op,randomGamma:()=>Lp,randomNormal:()=>zp,randomStandardNormal:()=>Pp,randomUniform:()=>Bp,randomUniformInt:()=>Wp,range:()=>Up,ready:()=>Si,real:()=>Yu,reciprocal:()=>Vp,registerBackend:()=>Ai,registerCallbackConstructor:()=>Cv,registerGradient:()=>As,registerKernel:()=>Es,registerOp:()=>BS,regularizers:()=>N,relu:()=>Gp,relu6:()=>jp,removeBackend:()=>Ci,reshape:()=>vc,reverse:()=>Hp,reverse1d:()=>qp,reverse2d:()=>Kp,reverse3d:()=>Xp,reverse4d:()=>Yp,rfft:()=>fd,round:()=>Jp,rsqrt:()=>Zp,scalar:()=>tu,scatterND:()=>zd,scatter_util:()=>p,searchSorted:()=>np,selu:()=>Qp,separableConv2d:()=>ed,sequential:()=>Sv,serialization:()=>i,setBackend:()=>Ni,setPlatform:()=>Oi,setWebGLContext:()=>Q_,setdiff1dAsync:()=>td,shared:()=>H,sigmoid:()=>Sc,sign:()=>nd,signal:()=>Jf,sin:()=>rd,sinh:()=>sd,slice:()=>Tc,slice1d:()=>ad,slice2d:()=>id,slice3d:()=>od,slice4d:()=>ud,slice_util:()=>d,softmax:()=>ld,softplus:()=>qh,spaceToBatchND:()=>Sp,sparse:()=>tm,sparseToDense:()=>Pd,spectral:()=>Yf,split:()=>dd,sqrt:()=>jo,square:()=>Ho,squaredDifference:()=>md,squeeze:()=>gd,stack:()=>yd,step:()=>bd,stridedSlice:()=>xd,string:()=>nm,sub:()=>du,sum:()=>Nh,sumOutType:()=>Aa,tan:()=>wd,tanh:()=>Cc,tensor:()=>ui,tensor1d:()=>vd,tensor2d:()=>kd,tensor3d:()=>Qu,tensor4d:()=>Id,tensor5d:()=>Nd,tensor6d:()=>Sd,tensorScatterUpdate:()=>Td,tensor_util:()=>s,test_util:()=>f,tidy:()=>wi,tile:()=>Rh,time:()=>Ii,topk:()=>Cd,train:()=>rm,transpose:()=>Ju,truncatedNormal:()=>$d,unique:()=>Ed,unregisterGradient:()=>Os,unregisterKernel:()=>Rs,unsortedSegmentSum:()=>Ad,unstack:()=>Rd,upcastType:()=>Ea,upperBound:()=>Od,util:()=>r,valueAndGrad:()=>Yo,valueAndGrads:()=>Jo,variable:()=>Fd,variableGrads:()=>Zo,version:()=>$j,version_converter:()=>oC,version_core:()=>Hl,version_cpu:()=>GA,version_layers:()=>Jw,version_webgl:()=>Oz,webgl:()=>_z,webgl_util:()=>q,where:()=>oh,whereAsync:()=>Dd,zeros:()=>up,zerosLike:()=>qo});var r={};n.r(r),n.d(r,{arraysEqual:()=>pe,arraysEqualWithNull:()=>he,assert:()=>ie,assertNonNegativeIntegerDimensions:()=>Ue,assertNonNull:()=>ue,assertShapesMatch:()=>oe,bytesFromStringArray:()=>$e,bytesPerElement:()=>Ce,checkConversionForErrors:()=>Ne,clamp:()=>ee,computeStrides:()=>De,convertBackendValuesAndArrayBuffer:()=>ze,createScalarValue:()=>Ys,createShuffledIndices:()=>ge,decodeString:()=>ta,distSquared:()=>ae,encodeString:()=>ea,fetch:()=>Qs,fingerPrint64:()=>Xs,flatten:()=>ra,getArrayFromDType:()=>Ie,getTypedArrayFromDType:()=>ke,hasEncodingLoss:()=>Te,hexToLong:()=>zs,indexToLoc:()=>Ge,inferDtype:()=>Oe,inferFromImplicitShape:()=>xe,isBoolean:()=>Ae,isFunction:()=>Fe,isInt:()=>de,isNumber:()=>Re,isPromise:()=>je,isScalarShape:()=>ce,isString:()=>Ee,isTypedArray:()=>na,isValidDtype:()=>Se,locToIndex:()=>Ve,makeOnesTypedArray:()=>Pe,makeZerosNestedTypedArray:()=>We,makeZerosTypedArray:()=>Be,nearestDivisor:()=>_e,nearestLargerEven:()=>te,now:()=>Zs,parseAxisParam:()=>we,randUniform:()=>se,repeatedTry:()=>be,rightPad:()=>ye,shuffle:()=>Z,shuffleCombo:()=>Q,sizeFromShape:()=>le,sizeToSquarishShape:()=>me,squeezeShape:()=>ve,sum:()=>re,swap:()=>ne,tanh:()=>fe,toNestedArray:()=>Le,toTypedArray:()=>Js});var s={};n.r(s),n.d(s,{assertTypesMatch:()=>_a,getTensorsInContainer:()=>Ma,isTensorInList:()=>Da,makeTypesMatch:()=>Fa});var a={};n.r(a),n.d(a,{isBrowser:()=>Ka,isMobile:()=>qa,mockIsMobile:()=>Ha});var i={};n.r(i),n.d(i,{Serializable:()=>su,SerializationMap:()=>au,getRegisteredName:()=>ou,registerClass:()=>iu});var o={};n.r(o),n.d(o,{assertAndGetBroadcastShape:()=>bu,getBroadcastDims:()=>gu,getReductionAxes:()=>yu});var u={};n.r(u),n.d(u,{CompositeArrayBuffer:()=>ci,browserFiles:()=>$u,browserHTTPRequest:()=>Lu,concatenateArrayBuffers:()=>ji,copyModel:()=>Ro,decodeWeights:()=>Mi,decodeWeightsStream:()=>Wi,encodeWeights:()=>Di,fromMemory:()=>Uu,fromMemorySync:()=>Vu,getLoadHandlers:()=>no,getModelArtifactsForJSON:()=>Xi,getModelArtifactsForJSONSync:()=>Ki,getModelArtifactsInfoForJSON:()=>Yi,getSaveHandlers:()=>to,getWeightSpecs:()=>Ji,http:()=>Mu,isHTTPScheme:()=>_u,listModels:()=>Eo,loadWeights:()=>Ru,moveModel:()=>Oo,registerLoadRouter:()=>eo,registerSaveRouter:()=>Qi,removeModel:()=>Ao,weightsLoaderFactory:()=>Ou,withSaveHandler:()=>Gu,withSaveHandlerSync:()=>ju});var l={};n.r(l),n.d(l,{confusionMatrix:()=>Zu});var c={};n.r(c),n.d(c,{draw:()=>ol,fromPixels:()=>ul,fromPixelsAsync:()=>sl,toPixels:()=>il});var h={};n.r(h),n.d(h,{prepareAndValidate:()=>ll});var p={};n.r(p),n.d(p,{calculateShapes:()=>pl,validateInput:()=>hl,validateUpdateShape:()=>cl});var d={};n.r(d),n.d(d,{assertParamsValid:()=>ml,computeFlatOffset:()=>$l,computeOutShape:()=>yl,getNormalizedAxes:()=>vl,isSliceContinous:()=>Cl,maskToAxes:()=>gl,parseSliceParams:()=>El,sliceInfo:()=>Al,startForAxis:()=>Sl,startIndicesWithElidedDims:()=>kl,stopForAxis:()=>Tl,stopIndicesWithElidedDims:()=>Il,stridesForAxis:()=>Nl,stridesWithElidedDims:()=>bl});var f={};n.r(f),n.d(f,{TEST_EPSILON_FLOAT16:()=>Fl,createVideoElement:()=>Gl,encodeStrings:()=>Vl,expectArrayBuffersEqual:()=>Ul,expectArraysClose:()=>_l,expectArraysEqual:()=>zl,expectNumbersClose:()=>Pl,expectPromiseToFail:()=>Ll,expectValuesInRange:()=>Wl,play:()=>jl,testEpsilon:()=>Dl});var m={};n.r(m),n.d(m,{conv2d:()=>Yd,depthwiseConv2d:()=>Qd,matMul:()=>ef});var g={};n.r(g),n.d(g,{collectGatherOpShapeInfo:()=>ug,computeOutShape:()=>og,segOpComputeOptimalWindowSize:()=>ig});var y={};n.r(y),n.d(y,{ERF_A1:()=>Nm,ERF_A2:()=>Sm,ERF_A3:()=>Tm,ERF_A4:()=>Cm,ERF_A5:()=>$m,ERF_P:()=>Im,PARALLELIZE_THRESHOLD:()=>dm,RowPartitionType:()=>um,SELU_SCALE:()=>km,SELU_SCALEALPHA:()=>vm,applyActivation:()=>Kd,assertAndGetBroadcastShape:()=>bu,assertAxesAreInnerMostDims:()=>bh,assertParamsConsistent:()=>im,assignToTypedArray:()=>_m,axesAreInnerMostDims:()=>fh,calculateShapes:()=>pl,checkEinsumDimSizes:()=>Vm,checkPadOnDimRoundingMode:()=>wc,combineLocations:()=>mh,combineRaggedTensorToTensorShapes:()=>lm,complexWithEvenIndex:()=>Rm,complexWithOddIndex:()=>Om,computeConv2DInfo:()=>lc,computeConv3DInfo:()=>cc,computeDefaultPad:()=>hc,computeDilation2DInfo:()=>ic,computeOptimalWindowSize:()=>fm,computeOutAndReduceShapes:()=>gh,computeOutShape:()=>om,computePool2DInfo:()=>oc,computePool3DInfo:()=>uc,convertConv2DDataFormat:()=>xc,decodeEinsumEquation:()=>Wm,eitherStridesOrDilationsAreOne:()=>yc,expandShapeToKeepDim:()=>yh,exponent:()=>Mm,exponents:()=>Dm,fromStringArrayToUint8:()=>cg,fromUint8ToStringArray:()=>lg,getAxesPermutation:()=>xh,getBroadcastDims:()=>gu,getComplexWithIndex:()=>Fm,getEinsumComputePath:()=>Gm,getEinsumPermutation:()=>Um,getFusedBiasGradient:()=>qd,getFusedDyActivation:()=>Hd,getImageCenter:()=>mm,getInnerMostAxes:()=>vh,getPermuted:()=>ym,getRaggedRank:()=>hm,getReductionAxes:()=>yu,getReshaped:()=>gm,getReshapedPermuted:()=>bm,getRowPartitionTypesHelper:()=>cm,getSliceBeginCoords:()=>xm,getSliceSize:()=>wm,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>Km,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>Xm,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>Ym,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>Qm,getSparseReshapeInputOutputMismatchErrorMessage:()=>tg,getSparseReshapeInputOutputMultipleErrorMessage:()=>eg,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>Jm,getSparseReshapeNegativeOutputDimErrorMessage:()=>Zm,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>ag,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>ng,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>rg,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>sg,getUndoAxesPermutation:()=>wh,isIdentityPermutation:()=>jm,log:()=>Is,mergeRealAndImagArrays:()=>Em,prepareAndValidate:()=>ll,prepareSplitSize:()=>qm,segment_util:()=>g,shouldFuse:()=>Xd,slice_util:()=>d,splitRealAndImagArrays:()=>Am,stridesOrDilationsArePositive:()=>bc,tupleValuesAreOne:()=>gc,upcastType:()=>Ea,validateDefaultValueShape:()=>pm,validateInput:()=>hl,validateUpdateShape:()=>cl,warn:()=>ks});var b={};n.r(b),n.d(b,{nonMaxSuppressionV3Impl:()=>mf,nonMaxSuppressionV4Impl:()=>gf,nonMaxSuppressionV5Impl:()=>yf,whereImpl:()=>_d});var x={};n.r(x),n.d(x,{maxNorm:()=>Vx,minMaxNorm:()=>Hx,nonNeg:()=>jx,unitNorm:()=>Gx});var w={};n.r(w),n.d(w,{constant:()=>Xx,glorotNormal:()=>nw,glorotUniform:()=>tw,heNormal:()=>rw,heUniform:()=>sw,identity:()=>Qx,leCunNormal:()=>aw,leCunUniform:()=>iw,ones:()=>Kx,orthogonal:()=>ow,randomNormal:()=>Jx,randomUniform:()=>Yx,truncatedNormal:()=>Zx,varianceScaling:()=>ew,zeros:()=>qx});var v={};n.r(v),n.d(v,{Layer:()=>kx,RNN:()=>$k,RNNCell:()=>Ek,activation:()=>iN,add:()=>mN,alphaDropout:()=>aS,average:()=>gN,averagePooling1d:()=>SN,averagePooling2d:()=>$N,averagePooling3d:()=>RN,avgPool1d:()=>TN,avgPool2d:()=>EN,avgPool3d:()=>ON,avgPooling1d:()=>CN,avgPooling2d:()=>AN,avgPooling3d:()=>FN,batchNormalization:()=>kN,bidirectional:()=>JN,categoryEncoding:()=>cS,centerCrop:()=>uS,concatenate:()=>yN,conv1d:()=>JI,conv2d:()=>ZI,conv2dTranspose:()=>QI,conv3d:()=>eN,conv3dTranspose:()=>tN,convLstm2d:()=>qN,convLstm2dCell:()=>KN,cropping2D:()=>rN,dense:()=>oN,depthwiseConv2d:()=>aN,dot:()=>vN,dropout:()=>uN,elu:()=>jI,embedding:()=>fN,flatten:()=>cN,gaussianDropout:()=>sS,gaussianNoise:()=>rS,globalAveragePooling1d:()=>_N,globalAveragePooling2d:()=>DN,globalMaxPool1d:()=>QN,globalMaxPool2d:()=>eS,globalMaxPooling1d:()=>MN,globalMaxPooling2d:()=>LN,gru:()=>WN,gruCell:()=>UN,input:()=>Tv,inputLayer:()=>GI,layerNormalization:()=>IN,leakyReLU:()=>qI,lstm:()=>VN,lstmCell:()=>GN,masking:()=>iS,maxPool1d:()=>tS,maxPool2d:()=>nS,maxPooling1d:()=>zN,maxPooling2d:()=>PN,maxPooling3d:()=>BN,maximum:()=>bN,minimum:()=>xN,multiply:()=>wN,permute:()=>dN,prelu:()=>KI,randomWidth:()=>hS,reLU:()=>HI,repeatVector:()=>hN,rescaling:()=>oS,reshape:()=>pN,resizing:()=>lS,rnn:()=>XN,separableConv2d:()=>nN,simpleRNN:()=>jN,simpleRNNCell:()=>HN,softmax:()=>XI,spatialDropout1d:()=>lN,stackedRNNCells:()=>YN,thresholdedReLU:()=>YI,timeDistributed:()=>ZN,upSampling2d:()=>sN,zeroPadding2d:()=>NN});var k={};n.r(k),n.d(k,{MAPE:()=>kS,MSE:()=>SS,binaryAccuracy:()=>pS,binaryCrossentropy:()=>dS,categoricalAccuracy:()=>mS,categoricalCrossentropy:()=>gS,cosineProximity:()=>xS,mape:()=>IS,meanAbsoluteError:()=>wS,meanAbsolutePercentageError:()=>vS,meanSquaredError:()=>NS,mse:()=>TS,precision:()=>yS,recall:()=>bS,sparseCategoricalAccuracy:()=>fS});var I={};n.r(I),n.d(I,{modelFromJSON:()=>vv});var N={};n.r(N),n.d(N,{l1:()=>$S,l1l2:()=>CS,l2:()=>ES});var S={};n.r(S),n.d(S,{json:()=>JS});var T={};n.r(T),n.d(T,{json:()=>ZS});var C={};n.r(C),n.d(C,{json:()=>QS});var $={};n.r($),n.d($,{json:()=>eT});var E={};n.r(E),n.d(E,{json:()=>tT});var A={};n.r(A),n.d(A,{json:()=>nT});var R={};n.r(R),n.d(R,{json:()=>rT});var O={};n.r(O),n.d(O,{json:()=>sT});var F={};n.r(F),n.d(F,{json:()=>aT});var _={};n.r(_),n.d(_,{json:()=>iT});var D={};n.r(D),n.d(D,{json:()=>oT});var M={};n.r(M),n.d(M,{json:()=>uT});var L={};n.r(L),n.d(L,{json:()=>lT});var z={};n.r(z),n.d(z,{json:()=>cT});var P={};n.r(P),n.d(P,{json:()=>hT});var B={};n.r(B),n.d(B,{json:()=>pT});var W={};n.r(W),n.d(W,{json:()=>dT});var U={};n.r(U),n.d(U,{json:()=>fT});var V={};n.r(V),n.d(V,{json:()=>mT});var G={};n.r(G),n.d(G,{OP_SCOPE_SUFFIX:()=>si,abs:()=>mu,acos:()=>Kl,acosh:()=>Xl,add:()=>Wo,addN:()=>Yl,all:()=>Jl,any:()=>Zl,argMax:()=>Ql,argMin:()=>ec,asin:()=>tc,asinh:()=>nc,atan:()=>rc,atan2:()=>sc,atanh:()=>ac,avgPool:()=>kc,avgPool3d:()=>Ic,basicLSTMCell:()=>$c,batchNorm:()=>Ac,batchNorm2d:()=>Rc,batchNorm3d:()=>Oc,batchNorm4d:()=>Fc,batchToSpaceND:()=>Ec,bincount:()=>_c,bitwiseAnd:()=>Dc,booleanMaskAsync:()=>Md,broadcastArgs:()=>Mc,broadcastTo:()=>Lc,buffer:()=>Mo,cast:()=>Lo,ceil:()=>zc,clipByValue:()=>Pc,clone:()=>zo,complex:()=>ii,concat:()=>Nc,concat1d:()=>Bc,concat2d:()=>Wc,concat3d:()=>Uc,concat4d:()=>Vc,conv1d:()=>jc,conv2d:()=>Gc,conv2dTranspose:()=>qc,conv3d:()=>Kc,conv3dTranspose:()=>Yc,cos:()=>Jc,cosh:()=>Zc,cosineWindow:()=>Vd,cumprod:()=>Qc,cumsum:()=>eh,denseBincount:()=>th,depthToSpace:()=>nh,depthwiseConv2d:()=>rh,diag:()=>sh,dilation2d:()=>ah,div:()=>Vo,divNoNan:()=>uh,dot:()=>lh,dropout:()=>Wd,einsum:()=>ch,elu:()=>hh,enclosingPowerOfTwo:()=>Ud,ensureShape:()=>ph,equal:()=>ih,erf:()=>dh,euclideanNorm:()=>Ch,exp:()=>$h,expandDims:()=>Eh,expm1:()=>Ah,eye:()=>Oh,fft:()=>cd,fill:()=>cu,floor:()=>Fh,floorDiv:()=>Uo,fused:()=>m,gather:()=>_h,gatherND:()=>Bd,greater:()=>Dh,greaterEqual:()=>Mh,ifft:()=>hd,imag:()=>Ku,image:()=>Zf,inTopKAsync:()=>Gd,irfft:()=>pd,isFinite:()=>Lh,isInf:()=>zh,isNaN:()=>Ph,leakyRelu:()=>Bh,less:()=>Wh,lessEqual:()=>Uh,linalg:()=>Qf,linspace:()=>Vh,localResponseNormalization:()=>Gh,log:()=>jh,log1p:()=>Hh,logSigmoid:()=>Kh,logSoftmax:()=>Xh,logSumExp:()=>Yh,logicalAnd:()=>Jh,logicalNot:()=>Zh,logicalOr:()=>Qh,logicalXor:()=>ep,losses:()=>em,lowerBound:()=>rp,matMul:()=>Hu,max:()=>kh,maxPool:()=>sp,maxPool3d:()=>ap,maxPoolWithArgmax:()=>ip,maximum:()=>xu,mean:()=>op,meshgrid:()=>cp,min:()=>Ih,minimum:()=>hp,mirrorPad:()=>pp,mod:()=>dp,moments:()=>fp,movingAverage:()=>Ld,mul:()=>Go,multiRNNCell:()=>mp,multinomial:()=>gp,neg:()=>Xu,norm:()=>Th,notEqual:()=>yp,oneHot:()=>qu,ones:()=>lp,onesLike:()=>bp,op:()=>ai,outerProduct:()=>xp,pad:()=>wp,pad1d:()=>vp,pad2d:()=>kp,pad3d:()=>Ip,pad4d:()=>Np,pool:()=>Tp,pow:()=>pu,prelu:()=>Cp,print:()=>Bo,prod:()=>$p,raggedGather:()=>Ep,raggedRange:()=>Ap,raggedTensorToTensor:()=>Rp,rand:()=>Op,randomGamma:()=>Lp,randomNormal:()=>zp,randomStandardNormal:()=>Pp,randomUniform:()=>Bp,randomUniformInt:()=>Wp,range:()=>Up,real:()=>Yu,reciprocal:()=>Vp,relu:()=>Gp,relu6:()=>jp,reshape:()=>vc,reverse:()=>Hp,reverse1d:()=>qp,reverse2d:()=>Kp,reverse3d:()=>Xp,reverse4d:()=>Yp,rfft:()=>fd,round:()=>Jp,rsqrt:()=>Zp,scalar:()=>tu,scatterND:()=>zd,searchSorted:()=>np,selu:()=>Qp,separableConv2d:()=>ed,setdiff1dAsync:()=>td,sigmoid:()=>Sc,sign:()=>nd,signal:()=>Jf,sin:()=>rd,sinh:()=>sd,slice:()=>Tc,slice1d:()=>ad,slice2d:()=>id,slice3d:()=>od,slice4d:()=>ud,softmax:()=>ld,softplus:()=>qh,spaceToBatchND:()=>Sp,sparse:()=>tm,sparseToDense:()=>Pd,spectral:()=>Yf,split:()=>dd,sqrt:()=>jo,square:()=>Ho,squaredDifference:()=>md,squeeze:()=>gd,stack:()=>yd,step:()=>bd,stridedSlice:()=>xd,string:()=>nm,sub:()=>du,sum:()=>Nh,tan:()=>wd,tanh:()=>Cc,tensor:()=>ui,tensor1d:()=>vd,tensor2d:()=>kd,tensor3d:()=>Qu,tensor4d:()=>Id,tensor5d:()=>Nd,tensor6d:()=>Sd,tensorScatterUpdate:()=>Td,tile:()=>Rh,topk:()=>Cd,transpose:()=>Ju,truncatedNormal:()=>$d,unique:()=>Ed,unsortedSegmentSum:()=>Ad,unstack:()=>Rd,upperBound:()=>Od,variable:()=>Fd,where:()=>oh,whereAsync:()=>Dd,zeros:()=>up,zerosLike:()=>qo});var j={};n.r(j),n.d(j,{CSVDataset:()=>XC,Dataset:()=>LC,FileDataSource:()=>l$,TextLineDataset:()=>UC,URLDataSource:()=>c$,array:()=>PC,csv:()=>h$,func:()=>p$,generator:()=>d$,microphone:()=>m$,version_data:()=>g$,webcam:()=>f$,zip:()=>BC});var H={};n.r(H),n.d(H,{addImpl:()=>D$,bincountImpl:()=>P$,bincountReduceImpl:()=>B$,bitwiseAndImpl:()=>W$,castImpl:()=>A$,ceilImpl:()=>q$,concatImpl:()=>Y$,equalImpl:()=>J$,expImpl:()=>eE,expm1Impl:()=>rE,floorDivImpl:()=>lE,floorImpl:()=>iE,gatherNdImpl:()=>pE,gatherV2Impl:()=>dE,greaterEqualImpl:()=>yE,greaterImpl:()=>fE,lessEqualImpl:()=>IE,lessImpl:()=>wE,linSpaceImpl:()=>TE,logImpl:()=>CE,maxImpl:()=>AE,maximumImpl:()=>RE,minimumImpl:()=>_E,multiplyImpl:()=>LE,negImpl:()=>WE,notEqualImpl:()=>VE,prodImpl:()=>XE,raggedGatherImpl:()=>ZE,raggedRangeImpl:()=>eA,raggedTensorToTensorImpl:()=>aA,rangeImpl:()=>iA,rsqrtImpl:()=>oA,scatterImpl:()=>cA,sigmoidImpl:()=>hA,simpleAbsImpl:()=>w$,sliceImpl:()=>fA,sparseFillEmptyRowsImpl:()=>yA,sparseReshapeImpl:()=>bA,sparseSegmentReductionImpl:()=>xA,sqrtImpl:()=>wA,squaredDifferenceImpl:()=>IA,staticRegexReplaceImpl:()=>TA,stridedSliceImpl:()=>EA,stringNGramsImpl:()=>RA,stringSplitImpl:()=>FA,stringToHashBucketFastImpl:()=>_A,subImpl:()=>DA,tileImpl:()=>PA,topKImpl:()=>UA,transposeImpl:()=>HE,uniqueImpl:()=>VA});var q={};n.r(q),n.d(q,{assertNotComplex:()=>iM,bindCanvasToFramebuffer:()=>_D,bindColorTextureToFramebuffer:()=>DD,bindTextureToProgramUniformSampler:()=>FD,bindTextureUnit:()=>ED,bindVertexBufferToProgramAttribute:()=>$D,callAndCheck:()=>lD,canBeRepresented:()=>pD,createFragmentShader:()=>gD,createFramebuffer:()=>CD,createProgram:()=>xD,createStaticIndexBuffer:()=>ID,createStaticVertexBuffer:()=>kD,createTexture:()=>SD,createVertexShader:()=>mD,getBatchDim:()=>WD,getExtensionOrThrow:()=>fD,getFramebufferErrorMessage:()=>zD,getMaxTexturesInShader:()=>ZD,getNumChannels:()=>ND,getProgramUniformLocation:()=>OD,getProgramUniformLocationOrThrow:()=>RD,getRowsCols:()=>UD,getShapeAs3D:()=>VD,getTextureShapeFromLogicalShape:()=>GD,getWebGLDisjointQueryTimerVersion:()=>QD,getWebGLErrorMessage:()=>dD,getWebGLMaxTextureSize:()=>XD,hasExtension:()=>eM,isCapableOfRenderingToFloatTexture:()=>nM,isDownloadFloatTextureEnabled:()=>rM,isReshapeFree:()=>HD,isWebGLFenceEnabled:()=>aM,isWebGLVersionEnabled:()=>tM,linkProgram:()=>wD,logShaderSourceAndInfoLog:()=>bD,resetMaxTextureSize:()=>YD,resetMaxTexturesInShader:()=>JD,unbindColorTextureFromFramebuffer:()=>MD,unbindTextureUnit:()=>AD,validateFramebuffer:()=>LD,validateProgram:()=>vD,validateTextureSize:()=>TD});var K={};n.r(K),n.d(K,{bindVertexProgramAttributeStreams:()=>JM,createBufferFromOutputTexture:()=>eL,createFloat16MatrixTexture:()=>GM,createFloat16PackedMatrixTexture:()=>YM,createFloat32MatrixTexture:()=>UM,createIndexBuffer:()=>PM,createPackedMatrixTexture:()=>KM,createUnsignedBytesMatrixTexture:()=>HM,createVertexBuffer:()=>zM,createVertexShader:()=>LM,downloadByteEncodedFloatMatrixFromOutputTexture:()=>nL,downloadFloat32MatrixFromBuffer:()=>tL,downloadMatrixFromPackedOutputTexture:()=>sL,downloadPackedMatrixFromBuffer:()=>rL,getInternalFormatForFloat16MatrixTexture:()=>VM,getInternalFormatForFloat16PackedMatrixTexture:()=>XM,getInternalFormatForFloat32MatrixTexture:()=>WM,getInternalFormatForPackedMatrixTexture:()=>qM,getInternalFormatForUnsignedBytesMatrixTexture:()=>jM,uploadDenseMatrixToTexture:()=>ZM,uploadPixelDataToTexture:()=>QM});class X{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class Y{refCount(e){return J("refCount")}incRef(e){return J("incRef")}timerAvailable(){return!0}time(e){return J("time")}read(e){return J("read")}readSync(e){return J("readSync")}readToGPU(e,t){return J("readToGPU")}numDataIds(){return J("numDataIds")}disposeData(e,t){return J("disposeData")}write(e,t,n){return J("write")}move(e,t,n,r,s){return J("move")}createTensorFromGPUData(e,t,n){return J("createTensorFromGPUData")}memory(){return J("memory")}floatPrecision(){return J("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return J("dispose")}}function J(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function Z(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,ne(e,t,n)}function Q(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,r=0;for(;n>0;)r=Math.random()*n|0,n--,ne(e,n,r),ne(t,n,r)}function ee(e,t,n){return Math.max(e,Math.min(t,n))}function te(e){return e%2==0?e:e+1}function ne(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function re(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function se(e,t){const n=Math.random();return t*n+(1-n)*e}function ae(e,t){let n=0;for(let r=0;r<e.length;r++){const s=Number(e[r])-Number(t[r]);n+=s*s}return n}function ie(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function oe(e,t,n=""){ie(pe(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function ue(e){ie(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function le(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function ce(e){return 0===e.length}function he(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(null!==e[n]&&null!==t[n]&&e[n]!==t[n])return!1;return!0}function pe(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function de(e){return e%1==0}function fe(e){if(null!=Math.tanh)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;{const t=Math.exp(2*e);return(t-1)/(t+1)}}function me(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function ge(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return Z(t),t}function ye(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function be(e,t=(e=>0),n,r){return new Promise(((s,a)=>{let i=0;const o=()=>{if(e())return void s();i++;const u=t(i);null!=n&&i>=n?a():null!=r?r(o,u):setTimeout(o,u)};o()}))}function xe(e,t){let n=1,r=-1;for(let t=0;t<e.length;++t)if(e[t]>=0)n*=e[t];else if(-1===e[t]){if(-1!==r)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${t}`);r=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===r){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const s=e.slice();return s[r]=t/n,s}function we(e,t){const n=t.length;return ie((e=null==e?t.map(((e,t)=>t)):[].concat(e)).every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),ie(e.every((e=>de(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function ve(e,t){const n=[],r=[],s=null!=t&&Array.isArray(t)&&0===t.length,a=null==t||s?null:we(t,e).sort();let i=0;for(let t=0;t<e.length;++t){if(null!=a){if(a[i]===t&&1!==e[t])throw new Error(`Can't squeeze axis ${t} since its dim '${e[t]}' is not 1`);(null==a[i]||a[i]>t)&&1===e[t]&&(n.push(e[t]),r.push(t)),a[i]<=t&&i++}1!==e[t]&&(n.push(e[t]),r.push(t))}return{newShape:n,keptDims:r}}function ke(e,t){return Ie(e,t)}function Ie(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function Ne(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type ${t} being uploaded contains ${r}.`)}}function Se(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}function Te(e,t){return!("complex64"===t||"float32"===t&&"complex64"!==e||"int32"===t&&"float32"!==e&&"complex64"!==e||"bool"===t&&"bool"===e)}function Ce(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function $e(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}function Ee(e){return"string"==typeof e||e instanceof String}function Ae(e){return"boolean"==typeof e}function Re(e){return"number"==typeof e}function Oe(e){return Array.isArray(e)?Oe(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":Re(e)?"float32":Ee(e)?"string":Ae(e)?"bool":"float32"}function Fe(e){return!!(e&&e.constructor&&e.call&&e.apply)}function _e(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function De(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function Me(e,t,n,r=!1){const s=new Array;if(1===t.length){const a=t[0]*(r?2:1);for(let t=0;t<a;t++)s[t]=n[e+t]}else{const a=t[0],i=t.slice(1),o=i.reduce(((e,t)=>e*t))*(r?2:1);for(let t=0;t<a;t++)s[t]=Me(e+t*o,i,n,r)}return s}function Le(e,t,n=!1){if(0===e.length)return t[0];const r=e.reduce(((e,t)=>e*t))*(n?2:1);if(0===r)return[];if(r!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return Me(0,e,t,n)}function ze(e,t){if(Array.isArray(e))return e;if("float32"===t)return e instanceof Float32Array?e:new Float32Array(e);if("int32"===t)return e instanceof Int32Array?e:new Int32Array(e);if("bool"===t||"string"===t)return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}function Pe(e,t){const n=Be(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function Be(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function We(e,t){const n=e.reduce(((e,t)=>e*t),1);if(null==t||"float32"===t)return Le(e,new Float32Array(n));if("int32"===t)return Le(e,new Int32Array(n));if("bool"===t)return Le(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function Ue(e){e.forEach((t=>{ie(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function Ve(e,t,n){if(0===t)return 0;if(1===t)return e[0];let r=e[e.length-1];for(let t=0;t<e.length-1;++t)r+=n[t]*e[t];return r}function Ge(e,t,n){if(0===t)return[];if(1===t)return[e];const r=new Array(t);for(let t=0;t<r.length-1;++t)r[t]=Math.floor(e/n[t]),e-=r[t]*n[t];return r[r.length-1]=e,r}function je(e){return e&&e.then&&"function"==typeof e.then}var He=n(96763);const qe="tfjsflags";class Ke{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=Xe,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(Ye().getBool("IS_TEST")||Ye().getBool("PROD")||He.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];Ye().getBool("IS_TEST")||Ye().getBool("PROD")||He.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(je(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getString(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(void 0===this.global||void 0===this.global.location||void 0===this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);qe in e&&e[qe].split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){const n=t.toLowerCase();return"true"===n||"false"===n?"true"===n:""+ +n===n?+n:t}(0,n)}))}}function Xe(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("=")))),t}function Ye(){return Je}let Je=null;var Ze=n(65606);let Qe;function et(){if(null==Qe){let e;if("undefined"!=typeof window)e=window;else if(void 0!==n.g)e=n.g;else if(void 0!==Ze)e=Ze;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}Qe=e}return Qe}function tt(e,t){const n=function(){const e=et();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const nt="Abs",rt="Acos",st="Acosh",at="Add",it="AddN",ot="All",ut="Any",lt="ArgMax",ct="ArgMin",ht="Asin",pt="Asinh",dt="Atan",ft="Atanh",mt="Atan2",gt="AvgPool",yt="AvgPoolGrad",bt="AvgPool3D",xt="AvgPool3DGrad",wt="BatchMatMul",vt="BatchToSpaceND",kt="Bincount",It="BitwiseAnd",Nt="BroadcastTo",St="BroadcastArgs",Tt="Cast",Ct="Ceil",$t="ClipByValue",Et="Complex",At="ComplexAbs",Rt="Concat",Ot="Conv2D",Ft="Conv2DBackpropFilter",_t="Conv2DBackpropInput",Dt="Conv3D",Mt="Conv3DBackpropFilterV2",Lt="Conv3DBackpropInputV2",zt="Cos",Pt="Cosh",Bt="Cumprod",Wt="Cumsum",Ut="CropAndResize",Vt="DenseBincount",Gt="DepthToSpace",jt="DepthwiseConv2dNative",Ht="DepthwiseConv2dNativeBackpropFilter",qt="DepthwiseConv2dNativeBackpropInput",Kt="Diag",Xt="Dilation2D",Yt="Dilation2DBackpropInput",Jt="Dilation2DBackpropFilter",Zt="Draw",Qt="RealDiv",en="Einsum",tn="Elu",nn="EluGrad",rn="Erf",sn="Equal",an="Exp",on="ExpandDims",un="Expm1",ln="FFT",cn="Fill",hn="FlipLeftRight",pn="Floor",dn="FloorDiv",fn="FusedBatchNorm",mn="GatherV2",gn="GatherNd",yn="Greater",bn="GreaterEqual",xn="Identity",wn="IFFT",vn="Imag",kn="IsFinite",In="IsInf",Nn="IsNan",Sn="LeakyRelu",Tn="Less",Cn="LessEqual",$n="LinSpace",En="Log",An="Log1p",Rn="LogicalAnd",On="LogicalNot",Fn="LogicalOr",_n="LogicalXor",Dn="LogSoftmax",Mn="LowerBound",Ln="LRN",zn="LRNGrad",Pn="MatrixBandPart",Bn="Max",Wn="Maximum",Un="MaxPool",Vn="MaxPoolGrad",Gn="MaxPool3D",jn="MaxPool3DGrad",Hn="MaxPoolWithArgmax",qn="Mean",Kn="Min",Xn="Minimum",Yn="MirrorPad",Jn="Mod",Zn="Multinomial",Qn="Multiply",er="Neg",tr="NotEqual",nr="NonMaxSuppressionV3",rr="NonMaxSuppressionV4",sr="NonMaxSuppressionV5",ar="OnesLike",ir="OneHot",or="Pack",ur="PadV2",lr="Pool",cr="Pow",hr="Prelu",pr="Prod",dr="RaggedGather",fr="RaggedRange",mr="RaggedTensorToTensor",gr="Range",yr="Real",br="Reciprocal",xr="Relu",wr="Reshape",vr="ResizeNearestNeighbor",kr="ResizeNearestNeighborGrad",Ir="ResizeBilinear",Nr="ResizeBilinearGrad",Sr="Relu6",Tr="Reverse",Cr="Round",$r="Rsqrt",Er="ScatterNd",Ar="TensorScatterUpdate",Rr="SearchSorted",Or="Select",Fr="Selu",_r="Slice",Dr="Sin",Mr="Sinh",Lr="Sign",zr="Sigmoid",Pr="Softplus",Br="Sqrt",Wr="Sum",Ur="SpaceToBatchND",Vr="SplitV",Gr="Softmax",jr="SparseFillEmptyRows",Hr="SparseReshape",qr="SparseSegmentMean",Kr="SparseSegmentSum",Xr="SparseToDense",Yr="SquaredDifference",Jr="Square",Zr="StaticRegexReplace",Qr="StridedSlice",es="StringNGrams",ts="StringSplit",ns="StringToHashBucketFast",rs="Sub",ss="Tan",as="Tanh",is="Tile",os="TopK",us="Transform",ls="Transpose",cs="Unique",hs="Unpack",ps="UnsortedSegmentSum",ds="UpperBound",fs="ZerosLike",ms="Step",gs="FromPixels",ys="RotateWithOffset",bs="_FusedMatMul",xs="FusedConv2D",ws="FusedDepthwiseConv2D";var vs=n(96763);function ks(...e){Ye().getBool("IS_TEST")||Ye().getBool("PROD")||vs.warn(...e)}function Is(...e){Ye().getBool("IS_TEST")||Ye().getBool("PROD")||vs.log(...e)}const Ns=tt("kernelRegistry",(()=>new Map)),Ss=tt("gradRegistry",(()=>new Map));function Ts(e,t){const n=_s(e,t);return Ns.get(n)}function Cs(e){return Ss.get(e)}function $s(e){const t=Ns.entries(),n=[];for(;;){const{done:r,value:s}=t.next();if(r)break;const[a,i]=s,[o]=a.split("_");o===e&&n.push(i)}return n}function Es(e){const{kernelName:t,backendName:n}=e,r=_s(t,n);Ns.has(r)&&ks(`The kernel '${t}' for backend '${n}' is already registered`),Ns.set(r,e)}function As(e){const{kernelName:t}=e;Ss.has(t)&&Ye().getBool("DEBUG")&&ks(`Overriding the gradient for '${t}'`),Ss.set(t,e)}function Rs(e,t){const n=_s(e,t);if(!Ns.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Ns.delete(n)}function Os(e){if(!Ss.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Ss.delete(e)}function Fs(e,t){$s(e).forEach((e=>{Es(Object.assign({},e,{backendName:t}))}))}function _s(e,t){return`${t}_${e}`}function Ds(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var Ms=n(28570);const Ls=n.n(Ms)()||Ms;function zs(e){return Ls.fromString(e,!0,16)}const Ps=zs("c3a5c85c97cb3127"),Bs=zs("b492b66fbe98f273"),Ws=zs("9ae16a3b2f90404f");function Us(e){return e.xor(e.shru(47))}function Vs(e,t,n){const r=e.slice(t,t+n);return Ls.fromBytes(Array.from(r),!0,!0)}function Gs(e,t){return Vs(e,t,8)}function js(e,t){return Vs(e,t,4)}function Hs(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function qs(e,t,n=zs("9ddfea08eb382d69")){let r=e.xor(t).mul(n);r=r.xor(r.shru(47));let s=t.xor(r).mul(n);return s=s.xor(s.shru(47)),s=s.mul(n),s}function Ks(e,t,n,r){return function(e,t,n,r,s,a){s=s.add(e),a=Hs(a.add(s).add(r),21);const i=s;return s=(s=s.add(t)).add(n),a=a.add(Hs(s,44)),[s.add(r),a.add(i)]}(Gs(e,t),Gs(e,t+8),Gs(e,t+16),Gs(e,t+24),n,r)}function Xs(e,t=e.length){const n=Ls.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=Ws.add(2*t),r=Gs(e,0).add(Ws),s=Gs(e,t-8);return qs(Hs(s,37).mul(n).add(r),Hs(r,25).add(s).mul(n),n)}if(t>=4){const n=Ws.add(2*t);return qs(js(e,0).shl(3).add(t),js(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return Us(Ws.mul(n).xor(Ps.mul(r))).mul(Ws)}return Ws}(e,t):function(e,t=e.length){const n=Ws.add(2*t),r=Gs(e,0).mul(Bs),s=Gs(e,8),a=Gs(e,t-8).mul(n),i=Gs(e,t-16).mul(Ws);return qs(Hs(r.add(s),43).add(Hs(a,30)).add(i),r.add(Hs(s.add(Ws),18)).add(a),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=Ws.add(2*t),r=Gs(e,0).mul(Ws),s=Gs(e,8),a=Gs(e,t-8).mul(n),i=Gs(e,t-16).mul(Ws),o=Hs(r.add(s),43).add(Hs(a,30)).add(i),u=qs(o,r.add(Hs(s.add(Ws),18)).add(a),n),l=Gs(e,16).mul(n),c=Gs(e,24),h=o.add(Gs(e,t-32)).mul(n),p=u.add(Gs(e,t-24)).mul(n);return qs(Hs(l.add(c),43).add(Hs(h,30)).add(p),l.add(Hs(c.add(r),18)).add(h),n)}(e,t);let r=n,s=n.mul(Bs).add(113),a=Us(s.mul(Ws).add(113)).mul(Ws),i=[Ls.UZERO,Ls.UZERO],o=[Ls.UZERO,Ls.UZERO];r=r.mul(Ws).add(Gs(e,0));let u=0;const l=64*(t-1>>6),c=l+(t-1&63)-63;do{r=Hs(r.add(s).add(i[0]).add(Gs(e,u+8)),37).mul(Bs),s=Hs(s.add(i[1]).add(Gs(e,u+48)),42).mul(Bs),r=r.xor(o[1]),s=s.add(i[0]).add(Gs(e,u+40)),a=Hs(a.add(o[0]),33).mul(Bs),i=Ks(e,u,i[1].mul(Bs),r.add(o[0])),o=Ks(e,u+32,a.add(o[1]),s.add(Gs(e,u+16))),[a,r]=[r,a],u+=64}while(u!==l);const h=Bs.add(a.and(255).shl(1));return u=c,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),r=Hs(r.add(s).add(i[0]).add(Gs(e,u+8)),37).mul(h),s=Hs(s.add(i[1]).add(Gs(e,u+48)),42).mul(h),r=r.xor(o[1].mul(9)),s=s.add(i[0].mul(9).add(Gs(e,u+40))),a=Hs(a.add(o[0]),33).mul(h),i=Ks(e,u,i[1].mul(h),r.add(o[0])),o=Ks(e,u+32,a.add(o[1]),s.add(Gs(e,u+16))),[a,r]=[r,a],qs(qs(i[0],o[0],h).add(Us(s).mul(Ps)).add(a),qs(i[1],o[1],h).add(r),h)}function Ys(e,t){return"string"===t?ea(e):Js([e],t)}function Js(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ra(e)),Ye().getBool("DEBUG")&&Ne(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error(`Unknown data type ${t}`)}function Zs(){return Ye().platform.now()}function Qs(e,t){return Ye().platform.fetch(e,t)}function ea(e,t="utf-8"){return t=t||"utf-8",Ye().platform.encode(e,t)}function ta(e,t="utf-8"){return t=t||"utf-8",Ye().platform.decode(e,t)}function na(e){return null!=Ye().platform.isTypedArray?Ye().platform.isTypedArray(e):Ds(e)}function ra(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||je(e)||null==e||na(e)&&n)t.push(e);else if(Array.isArray(e)||na(e))for(let r=0;r<e.length;++r)ra(e[r],t,n);else{let r=-1;for(const t of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(t)&&(r=Math.max(r,Number(t)));for(let s=0;s<=r;s++)ra(e[s],t,n)}return t}var sa=n(96763);class aa{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new oa)}profileKernel(e,t,n){let r;const s=()=>{r=n()};let a;const i=Zs();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(s);else{s();for(const e of r)e.dataSync();a=Promise.resolve({kernelMs:Zs()-i})}if(Ye().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<r.length;t++){const n=r[t];n.data().then((t=>{ia(t,n.dtype,e)}))}return{kernelName:e,outputs:r,inputs:t,timeMs:a.then((e=>e.kernelMs)),extraInfo:a.then((e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():""))}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:s,extraInfo:a}=e;n.forEach((e=>{Promise.all([e.data(),r,a]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],s,n[2])}))}))}}function ia(e,t,n){if("float32"!==t)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(isNaN(r)||!isFinite(r))return sa.warn(`Found ${r} in the result of '${n}'`),!0}return!1}class oa{logKernelProfile(e,t,n,r,s,a){const i="number"==typeof r?ye(`${r}ms`,9):r.error,o=ye(e,25),u=t.rank,l=t.size,c=ye(t.shape.toString(),14);let h="";for(const e in s){const n=s[e];if(null!=n){const r=n.shape||t.shape,s=r.length;h+=`${e}: ${s}D ${s>0?r:""} `}}sa.log(`%c${o}\t%c${i}\t%c${u}D ${c}\t%c${l}\t%c${h}\t%c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}const ua=20,la=3,ca=7;function ha(e,t,n,r){const s=De(t),a=function(e,t,n,r){const s=le(t),a=r[r.length-1],i=new Array(a).fill(0),o=t.length,u="complex64"===n?ma(e):e;if(o>1)for(let e=0;e<s/a;e++){const t=e*a;for(let e=0;e<a;e++)i[e]=Math.max(i[e],pa(u[t+e],0,n).length)}return i}(e,t,n,s),i=t.length,o=fa(e,t,n,s,a),u=["Tensor"];return r&&(u.push(` dtype: ${n}`),u.push(` rank: ${i}`),u.push(` shape: [${t}]`),u.push(" values:")),u.push(o.map((e=>" "+e)).join("\n")),u.join("\n")}function pa(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(ca))} + ${parseFloat(e[1].toFixed(ca))}j`:Ee(e)?`'${e}'`:"bool"===n?da(e):parseFloat(e.toFixed(ca)).toString(),ye(r,t)}function da(e){return 0===e?"false":"true"}function fa(e,t,n,r,s,a=!0){const i="complex64"===n?2:1,o=t[0],u=t.length;if(0===u)return"complex64"===n?[pa(ma(e)[0],0,n)]:"bool"===n?[da(e[0])]:[e[0].toString()];if(1===u){if(o>ua){const t=la*i;let r=Array.from(e.slice(0,t)),a=Array.from(e.slice((o-la)*i,o*i));return"complex64"===n&&(r=ma(r),a=ma(a)),["["+r.map(((e,t)=>pa(e,s[t],n))).join(", ")+", ..., "+a.map(((e,t)=>pa(e,s[o-la+t],n))).join(", ")+"]"]}return["["+("complex64"===n?ma(e):Array.from(e)).map(((e,t)=>pa(e,s[t],n))).join(", ")+"]"]}const l=t.slice(1),c=r.slice(1),h=r[0]*i,p=[];if(o>ua){for(let t=0;t<la;t++){const r=t*h,a=r+h;p.push(...fa(e.slice(r,a),l,n,c,s,!1))}p.push("...");for(let t=o-la;t<o;t++){const r=t*h,a=r+h;p.push(...fa(e.slice(r,a),l,n,c,s,t===o-1))}}else for(let t=0;t<o;t++){const r=t*h,a=r+h;p.push(...fa(e.slice(r,a),l,n,c,s,t===o-1))}const d=2===u?",":"";p[0]="["+(o>0?p[0]+d:"");for(let e=1;e<p.length-1;e++)p[e]=" "+p[e]+d;let f=",\n";for(let e=2;e<u;e++)f+="\n";return p[p.length-1]=" "+p[p.length-1]+"]"+(a?"":f),p}function ma(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class ga{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=le(e),null!=n){const e=n.length;ie(e===this.size,(()=>`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`))}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||Ie(t,this.size),this.strides=De(e)}set(e,...t){0===t.length&&(t=[0]),ie(t.length===this.rank,(()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`));const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;t<e.length-1;++t)n+=this.strides[t]*e[t];return this.values[n]}locToIndex(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(0===this.rank)return[];if(1===this.rank)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return ya().makeTensor(this.values,this.shape,this.dtype)}}let ya=null,ba=null,xa=null;class wa{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=le(e),this.strides=De(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return ba.buffer(this.shape,this.dtype,e)}bufferSync(){return ba.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Le(this.shape,e,"complex64"===this.dtype)}arraySync(){return Le(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=ya().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map((e=>ta(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),ya().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=ya().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>ta(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await ya().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),ya().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return ba.print(this,e)}clone(){return this.throwIfDisposed(),ba.clone(this)}toString(e=!1){return ha(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),ba.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),ya().makeVariable(this,e,t,n)}}function va(){return tt("Tensor",(()=>wa))}Object.defineProperty(wa,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),va();class ka extends wa{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!pe(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);ya().disposeTensor(this),this.dataId=e.dataId,ya().incRef(this,null)}dispose(){ya().disposeVariable(this),this.isDisposedInternal=!0}}var Ia,Na,Sa,Ta,Ca;Object.defineProperty(ka,Symbol.hasInstance,{value:e=>e instanceof wa&&null!=e.assign&&e.assign instanceof Function}),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(Ia||(Ia={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Na||(Na={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Sa||(Sa={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(Ta||(Ta={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Ca||(Ca={}));const $a={float32:Ta,int32:Na,bool:Sa,complex64:Ca};function Ea(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return $a[e][t]}function Aa(e){return Ea(e,"int32")}function Ra(e){return null!=e&&"object"==typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function Oa(e){return"undefined"!=typeof GPUBuffer&&null!=e&&"object"==typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Fa(e,t){if(e.dtype===t.dtype)return[e,t];const n=Ea(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function _a(e,t){ie(e.dtype===t.dtype,(()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`))}function Da(e,t){return t.some((t=>t.id===e.id))}function Ma(e){const t=[];return La(e,t,new Set),t}function La(e,t,n){if(null==e)return;if(e instanceof wa)return void t.push(e);if(r=e,!Array.isArray(r)&&"object"!=typeof r)return;var r;const s=e;for(const e in s){const r=s[e];n.has(r)||(n.add(r),La(r,t,n))}}var za=n(96763);function Pa(e){return null!=e.kernelName}class Ba{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map((e=>e.name))))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class Wa{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Ba}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void await this.setBackend(n)}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(null!=this.pendingBackendInit)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(ks(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new aa(this.backendInstance),!0}setupRegisteredKernels(){$s(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){$s(e).forEach((t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])}))}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof Y||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,r=n.then((n=>!(t<this.pendingBackendInitId||(this.registry[e]=n,this.pendingBackendInit=null,0)))).catch((n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,ks(`Initialization of backend ${e} failed`),ks(n.stack||n.message)),!1)));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}}catch(t){return ks(`Initialization of backend ${e} failed`),ks(t.stack||t.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:r,asyncInit:s}=this.initializeBackend(n);if(s||r)return{name:n,asyncInit:s}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),r=n.backend,s=this.readSync(t),a=r.refCount(t);r.disposeData(t,!0),n.backend=e,e.move(t,s,n.shape,n.dtype,a),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,r=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");r=e}return this.scopedRun((()=>this.startScope(r)),(()=>this.endScope(n)),(()=>(n=t(),n instanceof Promise&&za.error("Cannot return a Promise inside of tidy."),n)))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return Wa.nextTensorId++}nextVariableId(){return Wa.nextVariableId++}clone(e){const t=Va.runKernel(xn,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e};return Va.runKernel(Tt,t,{dtype:"float32"})}})),[],{}),t}runKernel(e,t,n){if(null==this.backendName&&this.backend,null==Ts(e,this.backendName))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let s=0;n.forEach((e=>{s+="complex64"===e.dtype?3:1}));const a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=r-t-s-a;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),s=this.state.numBytes,a=this.state.numTensors;let i,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const u=Pa(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(Pa(e)){const{kernelName:t,inputs:s,attrs:a}=e;null==this.backendName&&this.backend;const u=Ts(t,this.backendName);ie(null!=u,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),i=()=>{const e=this.backend.numDataIds();o=u.kernelFunc({inputs:s,attrs:a,backend:this.backend});const i=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,i);const l=i.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(r){const e=this.getTensorsForGradient(t,s,l);n=this.saveTensorsForBackwardMode(e)}return l}}else{const{forwardFunc:t}=e,s=e=>{r&&(n=e.map((e=>this.keep(this.clone(e)))))};i=()=>{const e=this.backend.numDataIds();o=this.tidy((()=>t(this.backend,s)));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,e,n),n}}const{inputs:l,attrs:c}=e,h=Pa(e)?null:e.backwardsFunc;let p;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(p=this.profiler.profileKernel(u,l,(()=>i())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs):t=i()})),r&&this.addTapeNode(u,l,t,h,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(l).map((e=>null!=l[e]?l[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const r=Cs(e);if(null!=r){const e=r.inputsToSave||[],s=r.outputsToSave||[];let a;r.saveAllInputs?(ie(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),a=Object.keys(t).map((e=>t[e]))):a=e.map((e=>t[e]));const i=n.filter(((e,t)=>s[t]));return a.concat(i)}return[]}makeTensor(e,t,n,r){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let s=e;"string"===n&&Ee(e[0])&&(s=e.map((e=>ea(e))));const a=r.write(s,t,n),i=new wa(t,n,a,this.nextTensorId());if(this.trackTensor(i,r),"string"===n){const e=this.state.tensorInfo.get(a),t=$e(s);this.state.numBytes+=t-e.bytes,e.bytes=t}return i}makeTensorFromDataId(e,t,n,r){const s={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(s,r)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:r,dtype:s}=e,a=new wa(r,s,n,this.nextTensorId());return this.trackTensor(a,t),a}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.cast(r));const s=new ka(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[s.name])throw new Error(`Variable with name ${s.name} was already registered`);return this.state.registeredVariables[s.name]=s,this.incRef(s,this.backend),s}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*Ce(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof ka||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*Ce(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((e=>e.totalBytesSnapshot))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,r,s,a){const i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:s},o=Cs(e);null!=o&&(r=o.gradFunc),null!=r&&(i.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],r=Be(e.size,e.dtype);return this.makeTensor(r,e.shape,e.dtype)}return e})),r(e.length>1?e:e[0],s,a))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=Ma(e),n=new Set(t.map((e=>e.id)));for(let e=0;e<this.state.activeScope.track.length;e++){const t=this.state.activeScope.track[e];t.kept||n.has(t.id)||t.dispose()}const r=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach((e=>{e.kept||e.scopeId!==r.id||this.track(e)}))}gradients(e,t,n,r=!1){if(ie(t.length>0,(()=>"gradients() received an empty list of xs.")),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const s=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));ie(s instanceof wa,(()=>"The result y returned by f() must be a tensor."));const a=function(e,t,n){const r={},s={};for(let e=0;e<t.length;e++)r[t[e].id]=!0;for(let n=0;n<e.length;n++){const a=e[n],i=a.inputs;for(const e in i){const n=i[e];let o=!1;for(let e=0;e<t.length;e++)if(r[n.id]){a.outputs.forEach((e=>r[e.id]=!0)),o=!0,s[a.id]=!0;break}if(o)break}}const a={};a[n.id]=!0;const i={};for(let t=e.length-1;t>=0;t--){const n=e[t],r=n.inputs;for(let e=0;e<n.outputs.length;e++)if(a[n.outputs[e].id]){for(const e in r)a[r[e].id]=!0,i[n.id]=!0;break}}const o=[];for(let t=0;t<e.length;t++){const n=e[t];if(s[n.id]&&i[n.id]){const e={};for(const t in n.inputs){const s=n.inputs[t];r[s.id]&&(e[t]=s)}const t=Object.assign({},n);t.inputs=e,t.outputs=n.outputs,o.push(t)}}return o}(this.state.activeTape,t,s);if(!r&&0===a.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(()=>{const e={};e[s.id]=null==n?function(e){const t=Pe(le(e),"float32");return Va.makeTensor(t,e,"float32")}(s.shape):n,function(e,t,n,r){for(let s=t.length-1;s>=0;s--){const a=t[s],i=[];if(a.outputs.forEach((t=>{const n=e[t.id];null!=n?i.push(n):i.push(null)})),null==a.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);const o=a.gradient(i);for(const t in a.inputs){if(!(t in o))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(o)}.`);const s=n((()=>o[t]()));if("float32"!==s.dtype)throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${s.dtype}'`);const i=a.inputs[t];if(!pe(s.shape,i.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${t}' has shape '${s.shape}', which does not match the shape of the input '${i.shape}'`);if(null==e[i.id])e[i.id]=s;else{const t=e[i.id];e[i.id]=r(t,s),t.dispose()}}}}(e,a,(e=>this.tidy(e)),Ga);const r=t.map((t=>e[t.id]));return 0===this.state.gradientDepth&&(this.state.activeTape.forEach((e=>{for(const t of e.saved)t.dispose()})),this.state.activeTape=null),{value:s,grads:r}}))}customGrad(e){return ie(Fe(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;ie(t.every((e=>e instanceof wa)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors"));const r={};return t.forEach(((e,t)=>{r[t]=e})),this.runKernelFunc({forwardFunc:(r,s)=>(n=e(...t,s),ie(n.value instanceof wa,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),ie(Fe(n.gradFunc),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.")),n.value),backwardsFunc:(e,r)=>{const s=n.gradFunc(e,r),a=Array.isArray(s)?s:[s];ie(a.length===t.length,(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...).")),ie(a.every((e=>e instanceof wa)),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."));const i={};return a.forEach(((e,t)=>{i[t]=()=>e})),i},inputs:r})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){const t=Zs(),n=await this.backend.time(e);return n.wallMs=Zs()-t,n}track(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Ba;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function Ua(){const e=et();if(null==e._tfengine){const t=new Ke(e);e._tfengine=new Wa(t)}var t;return t=e._tfengine.ENV,Je=t,ya=()=>e._tfengine,e._tfengine}Wa.nextTensorId=0,Wa.nextVariableId=0;const Va=Ua();function Ga(e,t){const n={a:e,b:t};return Va.runKernel(at,n)}let ja;function Ha(e){ja=e}function qa(e){if(void 0!==ja)return ja;if(e||"undefined"!=typeof navigator&&null!=navigator){if(e||(e=navigator),"ReactNative"===e.product)return!0;const t=e.userAgent||e.vendor||("undefined"!=typeof window?window.opera:"");if(!t){const t=e;return t.userAgentData&&t.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/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(t.substr(0,4))}return!1}function Ka(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var Xa=n(96763),Ya=n(65606);const Ja=Ye();function Za(e,t){let n=e;if(na(e))return"string"===t?[]:[e.length];if(Ra(e)){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if(Oa(e))return[e.buffer.size/(null==t?4:Ce(t))];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||na(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&Ye().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Qa(e,r,[]),r}function Qa(e,t,n){if(n=n||[],!Array.isArray(e)&&!na(e))return void ie(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));ie(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),ie(e.length===t[0],(()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`));const r=t.slice(1);for(let t=0;t<e.length;++t)Qa(e[t],r,n.concat(t))}function ei(e,t,n,r){if("string_or_numeric"!==e){if(null==e)throw new Error("Expected dtype cannot be null.");if("numeric"!==e&&e!==t||"numeric"===e&&"string"===t)throw new Error(`Argument '${n}' passed to '${r}' must be ${e} tensor, but got ${t} tensor`)}}function ti(e,t,n,r="numeric"){if(e instanceof va())return ei(r,e.dtype,t,n),e;let s=Oe(e);if("string"!==s&&["bool","int32","float32"].indexOf(r)>=0&&(s=r),ei(r,s,t,n),null==e||!na(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const r=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${r}'`)}const a=Za(e,s);na(e)||Array.isArray(e)||(e=[e]);const i="string"!==s?Js(e,s):ra(e,[],!0);return Va.makeTensor(i,a,s)}function ni(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map(((e,s)=>ti(e,`${t}[${s}]`,n,r)))}Ja.registerFlag("DEBUG",(()=>!1),(e=>{e&&Xa.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")})),Ja.registerFlag("IS_BROWSER",(()=>Ka())),Ja.registerFlag("IS_NODE",(()=>void 0!==Ya&&void 0!==Ya.versions&&void 0!==Ya.versions.node)),Ja.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),Ja.registerFlag("IS_SAFARI",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor))),Ja.registerFlag("PROD",(()=>!1)),Ja.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>Ja.getBool("DEBUG"))),Ja.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),Ja.registerFlag("IS_TEST",(()=>!1)),Ja.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>Ja.getBool("DEBUG"))),Ja.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1)),Ja.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",(()=>!1)),Ja.registerFlag("USE_SETTIMEOUTCUSTOM",(()=>!1));var ri=n(96763);const si="__op";function ai(e){const t=Object.keys(e);if(1!==t.length)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+=si;const s=(...e)=>{Va.startScope(n);try{const t=r(...e);return je(t)&&ri.error("Cannot return a Promise inside of tidy."),Va.endScope(t),t}catch(e){throw Va.endScope(null),e}};return Object.defineProperty(s,"name",{value:n,configurable:!0}),s}const ii=ai({complex_:function(e,t){const n=ti(e,"real","complex"),r=ti(t,"imag","complex");oe(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const s={real:n,imag:r};return Va.runKernel(Et,s)}});function oi(e,t,n,r){if(null==r)r=Oe(e);else if("complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(Oa(e)||Ra(e)){if("float32"!==r&&"int32"!==r)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${r}.`);return Va.backend.createTensorFromGPUData(e,t||n,r)}if(!na(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){Ue(t);const e=le(t),r=le(n);ie(e===r,(()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${r}`));for(let e=0;e<n.length;++e){const r=n[e],s=e!==n.length-1||r!==le(t.slice(e));ie(n[e]===t[e]||!s,(()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return na(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?Js(e,r):ra(e,[],!0),Va.makeTensor(e,t,r)}function ui(e,t,n){return oi(e,t,Za(e,n),n)}const li={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};class ci{static join(e){return new ci(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,null==e)return;if(e instanceof Array||(e=[e]),0===(e=e.map((e=>na(e)?e.buffer:e))).length)return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let n=0;n<e.length;n++){const r=e[n];n!==e.length-1&&r.byteLength!==this.bufferUniformSize&&(this.bufferUniformSize=void 0);const s=t+r.byteLength;this.shards.push({buffer:r,start:t,end:s}),t=s}0===this.shards.length&&(this.byteLength=0),this.byteLength=this.shards[this.shards.length-1].end}slice(e=0,t=this.byteLength){if(0===this.shards.length)return new ArrayBuffer(0);if(e=isNaN(Number(e))?0:e,t=isNaN(Number(t))?0:t,e=Math.max(0,e),(t=Math.min(this.byteLength,t))<=e)return new ArrayBuffer(0);const n=this.findShardForByte(e);if(-1===n)throw new Error(`Could not find start shard for byte ${e}`);const r=new ArrayBuffer(t-e),s=new Uint8Array(r);let a=0;for(let r=n;r<this.shards.length;r++){const n=this.shards[r],i=e+a-n.start,o=a,u=Math.min(t,n.end)-n.start,l=new Uint8Array(n.buffer,i,u-i);if(s.set(l,o),a+=l.length,t<n.end)break}return r}findShardForByte(e){if(0===this.shards.length||e<0||e>=this.byteLength)return-1;if(null!=this.bufferUniformSize)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(t){return e<t.start?-1:e>=t.end?1:0}if(0===t(this.shards[this.previousShardIndex]))return this.previousShardIndex;const n=function(e,t){let n=0,r=e.length;for(;n<=r;){const s=Math.floor((r-n)/2)+n,a=t(e[s]);if(0===a)return s;a<0?r=s:n=s+1}return-1}(this.shards,t);return-1===n?-1:(this.previousShardIndex=n,this.previousShardIndex)}}var hi=n(96763);function pi(){Ye().set("PROD",!0)}function di(){Ye().set("DEBUG",!0)}function fi(){Ye().set("DEPRECATION_WARNINGS_ENABLED",!1),hi.warn("TensorFlow.js deprecation warnings have been disabled.")}function mi(e){Ye().getBool("DEPRECATION_WARNINGS_ENABLED")&&hi.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function gi(){Va.disposeVariables()}function yi(){return Va}function bi(){return Va.memory()}function xi(e){return Va.profile(e)}function wi(e,t){return Va.tidy(e,t)}function vi(e){Ma(e).forEach((e=>e.dispose()))}function ki(e){return Va.keep(e)}function Ii(e){return Va.time(e)}function Ni(e){return Va.setBackend(e)}function Si(){return Va.ready()}function Ti(){return Va.backendName}function Ci(e){Va.removeBackend(e)}function $i(e){return Va.findBackend(e)}function Ei(e){return Va.findBackendFactory(e)}function Ai(e,t,n=1){return Va.registerBackend(e,t,n)}function Ri(){return Va.backend}function Oi(e,t){Ye().setPlatform(e,t)}xa=mi;var Fi=n(62045).hp;const _i=4;async function Di(e,t){const n=[],r=[],s=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);for(let a=0;a<s.length;++a){const i=s[a],o=Array.isArray(e)?e[a].tensor:e[i];if("float32"!==o.dtype&&"int32"!==o.dtype&&"bool"!==o.dtype&&"string"!==o.dtype&&"complex64"!==o.dtype)throw new Error(`Unsupported dtype in weight '${i}': ${o.dtype}`);const u={name:i,shape:o.shape,dtype:o.dtype};if("string"===o.dtype){const e=new Promise((async e=>{const t=await o.bytes(),n=t.reduce(((e,t)=>e+t.length),0)+_i*t.length,r=new Uint8Array(n);let s=0;for(let e=0;e<t.length;e++){const n=t[e],a=new Uint8Array(new Uint32Array([n.length]).buffer);r.set(a,s),s+=_i,r.set(n,s),s+=n.length}e(r)}));r.push(e)}else r.push(o.data());null!=t&&(u.group=t),n.push(u)}return{data:Ui(await Promise.all(r)),specs:n}}function Mi(e,t){const n=new ci(e),r={};let s=0;for(const e of t){const t=Li(e,((e,t)=>n.slice(s+e,s+t)));r[e.name]=Pi(e,n.slice(s,s+t)),s+=t}return r}function Li(e,t){const n=le(e.shape);let r;if("quantization"in e){const t=e.quantization;r=li[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r<n;r++)e+=_i+new Uint32Array(t(e,e+_i))[0];return e}r=li[e.dtype]}return n*r}async function zi(e,t){const n=le(e.shape);let r;if("quantization"in e){const t=e.quantization;r=li[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r<n;r++)e+=_i+new Uint32Array(await t(e,e+_i))[0];return e}r=li[e.dtype]}return n*r}function Pi(e,t){const n=e.name,r=e.dtype,s=e.shape,a=le(s);let i,o=0;if("quantization"in e){const s=e.quantization;if("uint8"===s.dtype||"uint16"===s.dtype){if(!("min"in s)||!("scale"in s))throw new Error(`Weight ${e.name} with quantization ${s.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==s.dtype)throw new Error(`Weight ${e.name} has unknown quantization dtype ${s.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==r)throw new Error(`Weight ${e.name} is quantized with ${s.dtype} which only supports weights of type float32 not ${r}.`)}const u=li[s.dtype],l="uint8"===s.dtype?new Uint8Array(t):new Uint16Array(t);if("float32"===r)if("uint8"===s.dtype||"uint16"===s.dtype){i=new Float32Array(l.length);for(let e=0;e<l.length;e++){const t=l[e];i[e]=t*s.scale+s.min}}else{if("float16"!==s.dtype)throw new Error(`Unsupported quantization type ${s.dtype} for weight type float32.`);{const e=function(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;!(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let e=1024;e<2048;e++)t[e]=939524096+(e-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return r=>{const s=new ArrayBuffer(4*r.length),a=new Uint32Array(s);for(let s=0;s<r.length;s++){const i=r[s],o=e[n[i>>10]+(1023&i)]+t[i>>10];a[s]=o}return new Float32Array(s)}}();i=e(l)}}else{if("int32"!==r)throw new Error(`Unsupported dtype in weight '${n}': ${r}`);if("uint8"!==s.dtype&&"uint16"!==s.dtype)throw new Error(`Unsupported quantization type ${s.dtype} for weight type int32.`);i=new Int32Array(l.length);for(let e=0;e<l.length;e++){const t=l[e];i[e]=Math.round(t*s.scale+s.min)}}o+=a*u}else if("string"===r){const n=le(e.shape);i=[];for(let e=0;e<n;e++){const e=new Uint32Array(t.slice(o,o+_i))[0];o+=_i;const n=new Uint8Array(t.slice(o,o+e));i.push(n),o+=e}}else{const e=li[r];if("float32"===r)i=new Float32Array(t);else if("int32"===r)i=new Int32Array(t);else{if("bool"!==r){if("complex64"===r){i=new Float32Array(t);const e=new Float32Array(i.length/2),n=new Float32Array(i.length/2);for(let t=0;t<e.length;t++)e[t]=i[2*t],n[t]=i[2*t+1];const r=ui(e,s,"float32"),a=ui(n,s,"float32"),o=ii(r,a);return r.dispose(),a.dispose(),o}throw new Error(`Unsupported dtype in weight '${n}': ${r}`)}i=new Uint8Array(t)}o+=a*e}return ui(i,s,r)}async function Bi(e,t,n){let r=new Uint8Array(t);for(;r.byteLength<n;){const{done:t,value:s}=await e.read();if(t&&null==s){const e=n-r.byteLength;throw new Error(`Reader is done but ${e} bytes are still expected`)}const a=new Uint8Array(r.length+s.byteLength);a.set(r,0),a.set(new Uint8Array(s),r.length),r=a}return r.buffer}async function Wi(e,t){const n={},r=e.getReader();let s=new ArrayBuffer(0);for(const e of t){const t=await zi(e,(async(e,t)=>(s=await Bi(r,s,t),s.slice(e,t))));s=await Bi(r,s,t);const a=s.slice(0,t);s=s.slice(t);const i=Pi(e,a);if(n[e.name]=i,"webgpu"===Ti()){const e=Ri();"uploadToGPU"in e&&le(i.shape)>=Ye().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&e.uploadToGPU(i.dataId)}}return n}function Ui(e){if(null===e)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach((e=>{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${e.constructor.name}`)}));const r=new Uint8Array(t);let s=0;return n.forEach((e=>{r.set(new Uint8Array(e.buffer),s),s+=e.byteLength})),r.buffer}const Vi=void 0!==Fi&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function Gi(e){return Vi?Fi.byteLength(e,"utf8"):new Blob([e]).size}function ji(e){return ci.join(e)}function Hi(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function qi(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(n.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),n}function Ki(e,t,n){const r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(r.trainingConfig=e.trainingConfig),null!=e.weightsManifest){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");r.weightSpecs=t,r.weightData=n}return null!=e.signature&&(r.signature=e.signature),null!=e.userDefinedMetadata&&(r.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(r.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(r.initializerSignature=e.initializerSignature),r}async function Xi(e,t){let n,r;return null!=e.weightsManifest&&([n,r]=await t(e.weightsManifest)),Ki(e,n,r)}function Yi(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:Gi(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:Gi(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:new ci(e.weightData).byteLength}}function Ji(e){const t=[];for(const n of e)t.push(...n.weights);return t}class Zi{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==Zi.instance&&(Zi.instance=new Zi),Zi.instance}static registerSaveRouter(e){Zi.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Zi.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Zi.getHandlers(e,"save")}static getLoadHandlers(e,t){return Zi.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?Zi.getInstance().loadRouters:Zi.getInstance().saveRouters).forEach((t=>{const s=t(e,n);null!==s&&r.push(s)})),r}}const Qi=e=>Zi.registerSaveRouter(e),eo=e=>Zi.registerLoadRouter(e),to=e=>Zi.getSaveHandlers(e),no=(e,t)=>Zi.getLoadHandlers(e,t),ro="tensorflowjs",so="models_store",ao="model_info_store";function io(){if(!Ye().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function oo(e){const t=e.result;t.createObjectStore(so,{keyPath:"modelPath"}),t.createObjectStore(ao,{keyPath:"modelPath"})}class uo{constructor(e){if(this.indexedDB=io(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise(((e,n)=>{const r=this.indexedDB.open(ro,1);r.onupgradeneeded=()=>oo(r),r.onsuccess=()=>{const s=r.result;if(null==t){const t=s.transaction(so,"readonly"),r=t.objectStore(so).get(this.modelPath);r.onsuccess=()=>{if(null==r.result)return s.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(r.result.modelArtifacts)},r.onerror=e=>(s.close(),n(r.error)),t.oncomplete=()=>s.close()}else{t.weightData=ci.join(t.weightData);const r=Yi(t),a=s.transaction(ao,"readwrite");let i,o,u=a.objectStore(ao);try{i=u.put({modelPath:this.modelPath,modelArtifactsInfo:r})}catch(e){return n(e)}i.onsuccess=()=>{o=s.transaction(so,"readwrite");const i=o.objectStore(so);let l;try{l=i.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r})}catch(e){return n(e)}l.onsuccess=()=>e({modelArtifactsInfo:r}),l.onerror=e=>{u=a.objectStore(ao);const t=u.delete(this.modelPath);t.onsuccess=()=>(s.close(),n(l.error)),t.onerror=e=>(s.close(),n(l.error))}},i.onerror=e=>(s.close(),n(i.error)),a.oncomplete=()=>{null==o?s.close():o.oncomplete=()=>s.close()}}},r.onerror=e=>n(r.error)}))}}uo.URL_SCHEME="indexeddb://";const lo=e=>{return Ye().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(uo.URL_SCHEME)?(t=e.slice(uo.URL_SCHEME.length),new uo(t)):null;var t};Zi.registerSaveRouter(lo),Zi.registerLoadRouter(lo);class co{constructor(){this.indexedDB=io()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(ro,1);n.onupgradeneeded=()=>oo(n),n.onsuccess=()=>{const r=n.result,s=r.transaction(ao,"readonly"),a=s.objectStore(ao).getAll();a.onsuccess=()=>{const t={};for(const e of a.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},a.onerror=e=>(r.close(),t(a.error)),s.oncomplete=()=>r.close()},n.onerror=e=>t(n.error)}))}async removeModel(e){var t;return e=(t=e).startsWith(uo.URL_SCHEME)?t.slice(uo.URL_SCHEME.length):t,new Promise(((t,n)=>{const r=this.indexedDB.open(ro,1);r.onupgradeneeded=()=>oo(r),r.onsuccess=()=>{const s=r.result,a=s.transaction(ao,"readwrite"),i=a.objectStore(ao),o=i.get(e);let u;o.onsuccess=()=>{if(null==o.result)return s.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const r=i.delete(e),a=()=>{u=s.transaction(so,"readwrite");const r=u.objectStore(so).delete(e);r.onsuccess=()=>t(o.result.modelArtifactsInfo),r.onerror=e=>n(o.error)};r.onsuccess=a,r.onerror=e=>(a(),s.close(),n(o.error))}},o.onerror=e=>(s.close(),n(o.error)),a.oncomplete=()=>{null==u?s.close():u.oncomplete=()=>s.close()}},r.onerror=e=>n(r.error)}))}}const ho="/",po="tensorflowjs_models",fo="info",mo="model_topology",go="weight_specs",yo="weight_data",bo="model_metadata";function xo(e){return{info:[po,e,fo].join(ho),topology:[po,e,mo].join(ho),weightSpecs:[po,e,go].join(ho),weightData:[po,e,yo].join(ho),modelMetadata:[po,e,bo].join(ho)}}function wo(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function vo(e){const t=e.split(ho);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(ho)}class ko{constructor(e){if(!Ye().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=xo(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),r=Yi(e),s=ci.join(e.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(Vi)return Fi.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,r=t.length;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}(s));const a={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:null!=e.signature?e.signature:void 0,userDefinedMetadata:null!=e.userDefinedMetadata?e.userDefinedMetadata:void 0,modelInitializer:null!=e.modelInitializer?e.modelInitializer:void 0,initializerSignature:null!=e.initializerSignature?e.initializerSignature:void 0,trainingConfig:null!=e.trainingConfig?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(a)),{modelArtifactsInfo:r}}catch(e){throw wo(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${r.modelTopologyBytes}, weightSpecsBytes=${r.weightSpecsBytes}, weightDataBytes=${r.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(null==e)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if("JSON"!==e.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(null==n)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;const r=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(null==r)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=r;const s=this.LS.getItem(this.keys.modelMetadata);if(null!=s){const e=JSON.parse(s);t.format=e.format,t.generatedBy=e.generatedBy,t.convertedBy=e.convertedBy,null!=e.signature&&(t.signature=e.signature),null!=e.userDefinedMetadata&&(t.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(t.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(t.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(t.trainingConfig=e.trainingConfig)}const a=this.LS.getItem(this.keys.weightData);if(null==a)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=function(e){if(Vi){const t=Fi.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n.set([t.charCodeAt(e)],e);return n.buffer}(a),t}}ko.URL_SCHEME="localstorage://";const Io=e=>{return Ye().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ko.URL_SCHEME)?(t=e.slice(ko.URL_SCHEME.length),new ko(t)):null;var t};Zi.registerSaveRouter(Io),Zi.registerLoadRouter(Io);class No{constructor(){ie(Ye().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),ie("undefined"==typeof window||void 0!==window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=po+ho,n=ho+fo;for(let r=0;r<this.LS.length;++r){const s=this.LS.key(r);s.startsWith(t)&&s.endsWith(n)&&(e[vo(s)]=JSON.parse(this.LS.getItem(s)))}return e}async removeModel(e){var t;const n=xo(e=(t=e).startsWith(ko.URL_SCHEME)?t.slice(ko.URL_SCHEME.length):t);if(null==this.LS.getItem(n.info))throw new Error(`Cannot find model at path '${e}'`);const r=JSON.parse(this.LS.getItem(n.info));return wo(n),r}}const So="://";class To{constructor(){this.managers={}}static getInstance(){return null==To.instance&&(To.instance=new To),To.instance}static registerManager(e,t){ie(null!=e,(()=>"scheme must not be undefined or null.")),e.endsWith(So)&&(e=e.slice(0,e.indexOf(So))),ie(e.length>0,(()=>"scheme must not be an empty string."));const n=To.getInstance();ie(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=To.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(To.getInstance().managers)}}function Co(e){if(-1===e.indexOf(So))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${To.getSchemes().join(",")}`);return{scheme:e.split(So)[0],path:e.split(So)[1]}}async function $o(e,t,n=!1){ie(e!==t,(()=>`Old path and new path are the same: '${e}'`));const r=Zi.getLoadHandlers(e);ie(r.length>0,(()=>`Copying failed because no load handler is found for source URL ${e}.`)),ie(r.length<2,(()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`));const s=r[0],a=Zi.getSaveHandlers(t);ie(a.length>0,(()=>`Copying failed because no save handler is found for destination URL ${t}.`)),ie(a.length<2,(()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`));const i=a[0],o=Co(e).scheme,u=Co(e).path,l=o===Co(e).scheme,c=await s.load();n&&l&&await To.getManager(o).removeModel(u);const h=await i.save(c);return n&&!l&&await To.getManager(o).removeModel(u),h.modelArtifactsInfo}async function Eo(){const e=To.getSchemes(),t={};for(const n of e){const e=await To.getManager(n).listModels();for(const r in e)t[n+So+r]=e[r]}return t}async function Ao(e){const t=Co(e);return To.getManager(t.scheme).removeModel(t.path)}async function Ro(e,t){return $o(e,t,!1)}async function Oo(e,t){return $o(e,t,!0)}class Fo{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){"undefined"!=typeof window&&Ye().getBool("USE_SETTIMEOUTCUSTOM")?(this.functionRefs.push(e),setTimeout((()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")}),t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",(e=>{e.source===window&&e.data.name===this.messageName&&(e.stopPropagation(),(0,this.functionRefs[e.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0))}),!0))):setTimeout(e,t)}isTypedArray(e){return Ds(e)}}if(Ye().get("IS_BROWSER")){Ye().setPlatform("browser",new Fo);try{To.registerManager(ko.URL_SCHEME,new No)}catch(e){}try{To.registerManager(uo.URL_SCHEME,new co)}catch(e){}}var _o=n(65606);let Do;function Mo(e,t="float32",n){return t=t||"float32",Ue(e),new ga(e,t,n)}Ye().get("IS_NODE")&&!Ye().get("IS_BROWSER")&&Ye().setPlatform("node",new class{constructor(){this.util=n(18590),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=Ye().global.fetch?Ye().global.fetch(e,t):(null==Do&&(Do=n(85817)),Do(e,t))}now(){const e=_o.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":new this.util.TextDecoder(t).decode(e)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}});const Lo=ai({cast_:function(e,t){const n=ti(e,"x","cast");if(!Se(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const r={x:n},s={dtype:t};return Va.runKernel(Tt,r,s)}}),zo=ai({clone_:function(e){const t={x:ti(e,"x","clone","string_or_numeric")};return Va.runKernel(xn,t)}});var Po=n(96763);function Bo(e,t=!1){Po.log(e.toString(t))}Ua(),ba={buffer:Mo,cast:Lo,clone:zo,print:Bo};const Wo=ai({add_:function(e,t){let n=ti(e,"a","add"),r=ti(t,"b","add");[n,r]=Fa(n,r);const s={a:n,b:r};return Va.runKernel(at,s)}}),Uo=ai({floorDiv_:function(e,t){let n=ti(e,"a","floorDiv"),r=ti(t,"b","floorDiv");[n,r]=Fa(n,r);const s={a:n,b:r};return Va.runKernel(dn,s)}}),Vo=ai({div_:function(e,t){let n=ti(e,"a","div"),r=ti(t,"b","div");if([n,r]=Fa(n,r),"int32"===n.dtype&&"int32"===r.dtype)return Uo(n,r);const s={a:n,b:r};return Va.runKernel(Qt,s,{})}}),Go=ai({mul_:function(e,t){let n=ti(e,"a","mul"),r=ti(t,"b","mul");[n,r]=Fa(n,r);const s={a:n,b:r};return Va.runKernel(Qn,s)}}),jo=ai({sqrt_:function(e){const t={x:ti(e,"x","sqrt","float32")};return Va.runKernel(Br,t)}}),Ho=ai({square_:function(e){const t=ti(e,"x","square");return Va.runKernel("Square",{x:t},{})}}),qo=ai({zerosLike_:function(e){const t={x:ti(e,"x","zerosLike")};return Va.runKernel(fs,t)}});function Ko(e){return ie(Fe(e),(()=>"The f passed in grad(f) must be a function")),(t,n)=>{const r=ti(t,"x","tf.grad","string_or_numeric"),s=null!=n?ti(n,"dy","tf.grad"):null;return Va.tidy((()=>{const{value:t,grads:n}=Va.gradients((()=>e(r)),[r],s);return null!=s&&oe(t.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),eu(n),n[0]}))}}function Xo(e){return ie(Fe(e),(()=>"The f passed in grads(f) must be a function")),(t,n)=>{ie(Array.isArray(t),(()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"));const r=ni(t,"args","tf.grads","string_or_numeric"),s=null!=n?ti(n,"dy","tf.grads"):null;return Va.tidy((()=>{const{value:t,grads:n}=Va.gradients((()=>e(...r)),r,s);return null!=s&&oe(t.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),eu(n),n}))}}function Yo(e){return ie(Fe(e),(()=>"The f passed in valueAndGrad(f) must be a function")),(t,n)=>{ie(t instanceof wa,(()=>"The x passed in valueAndGrad(f)(x) must be a tensor")),ie(null==n||n instanceof wa,(()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"));const{grads:r,value:s}=Va.gradients((()=>e(t)),[t],n);return eu(r),{grad:r[0],value:s}}}function Jo(e){return ie(Fe(e),(()=>"The f passed in valueAndGrads(f) must be a function")),(t,n)=>{ie(Array.isArray(t)&&t.every((e=>e instanceof wa)),(()=>"The args passed in valueAndGrads(f)(args) must be array of tensors")),ie(null==n||n instanceof wa,(()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"));const r=Va.gradients((()=>e(...t)),t,n);return null!=n&&oe(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),eu(r.grads),r}}function Zo(e,t){ie(Fe(e),(()=>"The f passed in variableGrads(f) must be a function")),ie(null==t||Array.isArray(t)&&t.every((e=>e instanceof ka)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in Va.registeredVariables)t.push(Va.registeredVariables[e])}const r=n?t.filter((e=>!e.trainable)):null,s=t.length;t=t.filter((e=>e.trainable)),ie(t.length>0,(()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${s} variables is trainable.`));const{value:a,grads:i}=Va.gradients(e,t,null,!0);ie(i.some((e=>null!=e)),(()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().")),ie(0===a.rank,(()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`));const o={};return t.forEach(((e,t)=>{null!=i[t]&&(o[e.name]=i[t])})),null!=r&&r.forEach((e=>o[e.name]=null)),{value:a,grads:o}}function Qo(e){return Va.customGrad(e)}function eu(e){if(e.filter((e=>null==e)).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}function tu(e,t){if((na(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&na(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return oi(e,[],[],t)}const nu=new Map,ru=new Map;class su{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class au{constructor(){this.classNameMap={}}static getMap(){return null==au.instance&&(au.instance=new au),au.instance}static register(e){au.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function iu(e,t,n){ie(null!=e.className,(()=>"Class being registered does not have the static className property defined.")),ie("string"==typeof e.className,(()=>"className is required to be a string, but got type "+typeof e.className)),ie(e.className.length>0,(()=>"Class being registered has an empty-string as its className, which is disallowed.")),void 0===t&&(t="Custom"),void 0===n&&(n=e.className);const r=t+">"+n;return au.register(e),nu.set(r,e),ru.set(e,r),e}function ou(e){return ru.has(e)?ru.get(e):e.className}class uu extends su{minimize(e,t=!1,n){const{value:r,grads:s}=this.computeGradients(e,n);if(null!=n){const e=n.map((e=>({name:e.name,tensor:s[e.name]})));this.applyGradients(e)}else this.applyGradients(s);return vi(s),t?r:(r.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Zo(e,t)}dispose(){null!=this.iterations_&&vi(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:tu(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(uu,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});class lu extends uu{static get className(){return"Adadelta"}constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=Va.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=Va.registeredVariables[t];null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:wi((()=>qo(r).variable(!1)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:wi((()=>qo(r).variable(!1)))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const a=this.accumulatedGrads[n].variable,i=this.accumulatedUpdates[n].variable;wi((()=>{const e=Wo(Go(a,this.rho),Go(Ho(s),1-this.rho)),t=Go(Vo(jo(Wo(i,this.epsilon)),jo(Wo(a,this.epsilon))),s),n=Wo(Go(i,this.rho),Go(Ho(t),1-this.rho));a.assign(e),i.assign(n);const o=Wo(Go(t,-this.learningRate),r);r.assign(o)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(vi(this.accumulatedGrads.map((e=>e.variable))),vi(this.accumulatedUpdates.map((e=>e.variable))))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){const t=(e=await this.extractIterations(e)).length/2;this.accumulatedGrads=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(!1)}))),this.accumulatedUpdates=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(!1)})))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}function cu(e,t,n){Ue(e);const r={shape:e,value:t,dtype:n=n||Oe(t)};return Va.runKernel(cn,{},r)}class hu extends uu{static get className(){return"Adagrad"}constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=Va.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:wi((()=>cu(r.shape,this.initialAccumulatorValue).variable(e)))}}const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const a=this.accumulatedGrads[n].variable;wi((()=>{const e=Wo(a,Ho(s));a.assign(e);const t=Wo(Go(Vo(s,jo(Wo(e,Va.backend.epsilon()))),-this.learningRate),r);r.assign(t)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&vi(this.accumulatedGrads.map((e=>e.variable)))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e),this.accumulatedGrads=e.map((e=>({originalName:e.name,variable:e.tensor.variable(!1)})))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}const pu=ai({pow_:function(e,t){let n=ti(e,"base","pow"),r=ti(t,"exp","pow");[n,r]=Fa(n,r);const s={a:n,b:r};return Va.runKernel(cr,s)}}),du=ai({sub_:function(e,t){let n=ti(e,"a","sub"),r=ti(t,"b","sub");[n,r]=Fa(n,r);const s={a:n,b:r};return Va.runKernel(rs,s)}});class fu extends uu{static get className(){return"Adam"}constructor(e,t,n,r=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],wi((()=>{this.accBeta1=tu(t).variable(),this.accBeta2=tu(n).variable()})),null==r&&(this.epsilon=Va.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);wi((()=>{const n=du(1,this.accBeta1),r=du(1,this.accBeta2);t.forEach(((t,s)=>{const a=Va.registeredVariables[t];null==this.accumulatedFirstMoment[s]&&(this.accumulatedFirstMoment[s]={originalName:`${t}/m`,variable:wi((()=>qo(a).variable(!1)))}),null==this.accumulatedSecondMoment[s]&&(this.accumulatedSecondMoment[s]={originalName:`${t}/v`,variable:wi((()=>qo(a).variable(!1)))});const i=Array.isArray(e)?e[s].tensor:e[t];if(null==i)return;const o=this.accumulatedFirstMoment[s].variable,u=this.accumulatedSecondMoment[s].variable,l=Wo(Go(o,this.beta1),Go(i,1-this.beta1)),c=Wo(Go(u,this.beta2),Go(Ho(i),1-this.beta2)),h=Vo(l,n),p=Vo(c,r);o.assign(l),u.assign(c);const d=Wo(Go(Vo(h,Wo(jo(p),this.epsilon)),-this.learningRate),a);a.assign(d)})),this.accBeta1.assign(Go(this.accBeta1,this.beta1)),this.accBeta2.assign(Go(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&vi(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&vi(this.accumulatedSecondMoment.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e),wi((()=>{this.accBeta1.assign(pu(this.beta1,this.iterations_+1)),this.accBeta2.assign(pu(this.beta2,this.iterations_+1))}));const t=e.length/2;this.accumulatedFirstMoment=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(!1)}))),this.accumulatedSecondMoment=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(!1)})))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}const mu=ai({abs_:function(e){const t=ti(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return Va.runKernel(At,e)}{const e={x:t};return Va.runKernel(nt,e)}}});function gu(e,t){const n=e.length,r=[];for(let s=0;s<n;s++){const a=n-1-s,i=e[a]||1;(t[t.length-1-s]||1)>1&&1===i&&r.unshift(a)}return r}function yu(e,t){const n=[];for(let r=0;r<t.length;r++){const s=e[e.length-r-1],a=t.length-r-1,i=t[a];(null==s||1===s&&i>1)&&n.unshift(a)}return n}function bu(e,t){const n=Math.max(e.length,t.length),r=new Array(n);for(let s=0;s<n;s++){let a=e[e.length-s-1];null==a&&(a=1);let i=t[t.length-s-1];if(null==i&&(i=1),1===a)r[n-s-1]=i;else if(1===i)r[n-s-1]=a;else{if(a!==i)throw Error(`Operands could not be broadcast together with shapes ${e} and ${t}.`);r[n-s-1]=a}}return r}const xu=ai({maximum_:function(e,t){let n=ti(e,"a","maximum"),r=ti(t,"b","maximum");[n,r]=Fa(n,r),"bool"===n.dtype&&(n=Lo(n,"int32"),r=Lo(r,"int32")),bu(n.shape,r.shape);const s={a:n,b:r};return Va.runKernel(Wn,s)}});class wu extends uu{static get className(){return"Adamax"}constructor(e,t,n,r=null,s=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.decay=s,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],wi((()=>{this.iteration=tu(0).variable(),this.accBeta1=tu(t).variable()})),null==r&&(this.epsilon=Va.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);wi((()=>{const n=du(1,this.accBeta1),r=Vo(-this.learningRate,Wo(Go(this.iteration,this.decay),1));t.forEach(((t,s)=>{const a=Va.registeredVariables[t];null==this.accumulatedFirstMoment[s]&&(this.accumulatedFirstMoment[s]={originalName:`${t}/m`,variable:qo(a).variable(!1)}),null==this.accumulatedWeightedInfNorm[s]&&(this.accumulatedWeightedInfNorm[s]={originalName:`${t}/v`,variable:qo(a).variable(!1)});const i=Array.isArray(e)?e[s].tensor:e[t];if(null==i)return;const o=this.accumulatedFirstMoment[s].variable,u=this.accumulatedWeightedInfNorm[s].variable,l=Wo(Go(o,this.beta1),Go(i,1-this.beta1)),c=Go(u,this.beta2),h=mu(i),p=xu(c,h);o.assign(l),u.assign(p);const d=Wo(Go(Vo(r,n),Vo(l,Wo(p,this.epsilon))),a);a.assign(d)})),this.iteration.assign(Wo(this.iteration,1)),this.accBeta1.assign(Go(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&vi(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&vi(this.accumulatedWeightedInfNorm.map((e=>e.variable)))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}class vu extends uu{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=Array.isArray(e)?e[n].tensor:e[t];if(null==r)return;const s=Va.registeredVariables[t];wi((()=>{const e=Wo(Go(this.c,r),s);s.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=ki(tu(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(0!==(e=await this.extractIterations(e)).length)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}class ku extends vu{static get className(){return"Momentum"}constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=tu(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=Va.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:wi((()=>qo(r).variable(e)))}}const s=this.accumulations[n].variable,a=Array.isArray(e)?e[n].tensor:e[t];null!=a&&wi((()=>{let e;const t=Wo(Go(this.m,s),a);e=this.useNesterov?Wo(Go(this.c,Wo(a,Go(t,this.m))),r):Wo(Go(this.c,t),r),s.assign(t),r.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&vi(this.accumulations.map((e=>e.variable)))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e),this.accumulations=e.map((e=>({originalName:e.name,variable:e.tensor.variable(!1)})))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}class Iu extends uu{static get className(){return"RMSProp"}constructor(e,t=.9,n=0,r=null,s=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=s,null==r&&(this.epsilon=Va.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=Va.registeredVariables[t],s=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:wi((()=>qo(r).variable(s)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:wi((()=>qo(r).variable(s)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:wi((()=>qo(r).variable(s)))});const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const i=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;wi((()=>{const e=Wo(Go(i,this.decay),Go(Ho(a),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,s=Wo(Go(t,this.decay),Go(a,1-this.decay)),u=Vo(Go(a,this.learningRate),jo(du(e,Wo(Ho(s),this.epsilon)))),l=Wo(Go(o,this.momentum),u);i.assign(e),t.assign(s),o.assign(l);const c=du(r,l);r.assign(c)}else{const e=Wo(Go(i,this.decay),Go(Ho(a),1-this.decay)),t=Wo(Go(o,this.momentum),Vo(Go(a,this.learningRate),jo(Wo(e,this.epsilon))));i.assign(e),o.assign(t);const n=du(r,t);r.assign(n)}}))})),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&vi(this.accumulatedMeanSquares.map((e=>e.variable))),null!=this.accumulatedMeanGrads&&this.centered&&vi(this.accumulatedMeanGrads.map((e=>e.variable))),null!=this.accumulatedMoments&&vi(this.accumulatedMoments.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.accumulatedMoments=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}const Nu=[lu,hu,fu,wu,ku,Iu,vu];function Su(e){return new Promise((e=>setTimeout(e))).then(e)}class Tu{constructor(e){if(!Ye().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Tu.URL_SCHEME)&&(e=e.slice(Tu.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelJsonFileName=e+".json",this.weightDataFileName=e+".weights.bin"}async save(e){if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=ci.join(e.weightData),n=window.URL.createObjectURL(new Blob([t],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const t=qi(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),r=window.URL.createObjectURL(new Blob([JSON.stringify(t)],{type:"application/json"})),s=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(s.download=this.modelJsonFileName,s.href=r,await Su((()=>s.dispatchEvent(new MouseEvent("click")))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=n,await Su((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:Yi(e)}}}}Tu.URL_SCHEME="downloads://";class Cu{constructor(e){if(null==e||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise(((e,t)=>{const n=new FileReader;n.onload=n=>{const r=JSON.parse(n.target.result),s=r.modelTopology;if(null==s)return void t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));if(null==r.weightsManifest)return void t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));if(0===this.weightsFiles.length)return void e({modelTopology:s});const a=Xi(r,(e=>this.loadWeights(e)));e(a)},n.onerror=e=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)}))}loadWeights(e){const t=[],n=[];for(const r of e)t.push(...r.weights),n.push(...r.paths);const r=this.checkManifestAndWeightFiles(e),s=n.map((e=>this.loadWeightsFile(e,r[e])));return Promise.all(s).then((e=>[t,e]))}loadWeightsFile(e,t){return new Promise(((n,r)=>{const s=new FileReader;s.onload=e=>{const t=e.target.result;n(t)},s.onerror=t=>r(`Failed to weights data from file of path '${e}'.`),s.readAsArrayBuffer(t)}))}checkManifestAndWeightFiles(e){const t=[],n=this.weightsFiles.map((e=>Hi(e.name))),r={};for(const s of e)s.paths.forEach((e=>{const s=Hi(e);if(-1!==t.indexOf(s))throw new Error(`Duplicate file basename found in weights manifest: '${s}'`);if(t.push(s),-1===n.indexOf(s))throw new Error(`Weight file with basename '${s}' is not provided.`);r[e]=this.weightsFiles[n.indexOf(s)]}));if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return r}}function $u(e){return new Cu(e)}function Eu(e,t,n,r){!function(e){ie(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){ie(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),ie(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),ie(t>=e,(()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction ${t}`))}(n=null==n?0:n,r=null==r?1:r);let s=0;return Promise.all(e.map((a=>(a.then((a=>{const i=n+ ++s/e.length*(r-n);return t(i),a})),a))))}async function Au(e,t){null==t&&(t={});const n=null==t.fetchFunc?Ye().platform.fetch:t.fetchFunc,r=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),s=(null==t.onProgress?await Promise.all(r):await Eu(r,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(s):await Eu(s,t.onProgress,.5,1)}async function Ru(e,t="",n,r){return Ou((e=>Au(e,{requestInit:r})))(e,t,n)}function Ou(e){return async(t,n="",r)=>{const s=t.map((()=>!1)),a={},i=null!=r?r.map((()=>!1)):[],o=[];if(t.forEach(((e,t)=>{let n=0;e.weights.forEach((e=>{const u="quantization"in e?e.quantization.dtype:e.dtype,l=li[u]*le(e.shape),c=()=>{s[t]=!0,null==a[t]&&(a[t]=[]),a[t].push({manifestEntry:e,groupOffset:n,sizeBytes:l})};null!=r?r.forEach(((t,n)=>{t===e.name&&(c(),i[n]=!0)})):c(),o.push(e.name),n+=l}))})),!i.every((e=>e))){const e=r.filter(((e,t)=>!i[t]));throw new Error(`Could not find weights in manifest with names: ${e.join(", ")}. \nManifest JSON has weights with names: ${o.join(", ")}.`)}const u=s.reduce(((e,t,n)=>(t&&e.push(n),e)),[]),l=[];u.forEach((e=>{t[e].paths.forEach((e=>{const t=n+(n.endsWith("/")?"":"/")+e;l.push(t)}))}));const c=await e(l),h={};let p=0;return u.forEach((e=>{const n=t[e].paths.length,r=new ci(c.slice(p,p+n));a[e].forEach((e=>{const t=Mi(r.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const e in t)h[e]=t[e]})),p+=n})),h}}Zi.registerSaveRouter((e=>Ye().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Tu.URL_SCHEME)?function(e="model"){return new Tu(e)}(e.slice(Tu.URL_SCHEME.length)):null));class Fu{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(ie("function"==typeof t.fetchFunc,(()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)")),this.fetch=t.fetchFunc):this.fetch=Ye().platform.fetch,ie(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&ie(2===e.length,(()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`)),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{},this.loadOptions=t}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=qi(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);if(t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData){const n=ci.join(e.weightData);t.body.append("model.weights.bin",new Blob([n],{type:"application/octet-stream"}),"model.weights.bin")}const r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:Yi(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async loadModelJSON(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(e){let t=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?t+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t)}const n=t.modelTopology,r=t.weightsManifest;if(null==n&&null==r)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return t}async load(){return this.loadOptions.streamWeights?this.loadStream():Xi(await this.loadModelJSON(),(e=>this.loadWeights(e)))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),n=Ji(e.weightsManifest);return Object.assign(Object.assign({},e),{weightSpecs:n,getWeightStream:()=>function(e,t){var n;const r=null==t.fetchFunc?Ye().platform.fetch:t.fetchFunc;let s,a=0;return null===(n=t.onProgress)||void 0===n||n.call(t,0),new ReadableStream({pull:async n=>{for(var i;a<e.length;){if(!s){const n=(await r(e[a],t.requestInit,{isBinary:!0})).body;s=n.getReader()}const{done:o,value:u}=await s.read();if(!o)return void n.enqueue(u);a++,s=void 0,null===(i=t.onProgress)||void 0===i||i.call(t,a/e.length)}n.close()}})}(t,this.loadOptions)})}async getWeightUrls(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=function(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?");return[e.substring(0,t)+"/",n>t?e.substring(n):""]}(t),s=this.weightPathPrefix||n,a=[],i=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?i.push(this.weightUrlConverter(e)):a.push(s+e+r);return this.weightUrlConverter&&a.push(...await Promise.all(i)),a}async loadWeights(e){const t=await this.getWeightUrls(e);return[Ji(e),await Au(t,this.loadOptions)]}}function _u(e){return null!=e.match(Fu.URL_SCHEME_REGEX)}Fu.URL_SCHEME_REGEX=/^https?:\/\//;const Du=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>_u(e))):_u(e),n)return Mu(e,t)}return null};function Mu(e,t){return new Fu(e,t)}function Lu(e,t){return Mu(e,t)}Zi.registerSaveRouter(Du),Zi.registerLoadRouter(Du);var zu=n(96763);class Pu{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class Bu{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class Wu{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function Uu(e,t,n,r){return new Wu(Vu(...arguments))}function Vu(e,t,n,r){return 1===arguments.length?null!=e.modelTopology||null!=e.weightSpecs?new Pu(e):(zu.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Pu({modelTopology:e})):(zu.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Pu({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r}))}function Gu(e){return new Bu(e)}function ju(e){return new Bu(e)}const Hu=ai({matMul_:function(e,t,n=!1,r=!1){let s=ti(e,"a","matMul"),a=ti(t,"b","matMul");[s,a]=Fa(s,a);const i={a:s,b:a},o={transposeA:n,transposeB:r};return Va.runKernel(wt,i,o)}}),qu=ai({oneHot_:function(e,t,n=1,r=0,s="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const a={indices:ti(e,"indices","oneHot","int32")},i={dtype:s,depth:t,onValue:n,offValue:r};return Va.runKernel(ir,a,i)}}),Ku=ai({imag_:function(e){const t={input:ti(e,"input","imag")};return Va.runKernel(vn,t)}}),Xu=ai({neg_:function(e){const t={x:ti(e,"x","neg")};return Va.runKernel(er,t)}}),Yu=ai({real_:function(e){const t={input:ti(e,"input","real")};return Va.runKernel(yr,t)}}),Ju=ai({transpose_:function(e,t,n){const r=ti(e,"x","transpose");if(null==t&&(t=r.shape.map(((e,t)=>t)).reverse()),ie(r.rank===t.length,(()=>`Error in transpose: rank of input ${r.rank} must match length of perm ${t}.`)),t.forEach((e=>{ie(e>=0&&e<r.rank,(()=>"All entries in 'perm' must be between 0 and "+(r.rank-1)+` but got ${t}`))})),r.rank<=1)return r.clone();const s={x:r},a={perm:t};return"complex64"===r.dtype?wi((()=>{let e=Yu(r),t=Ku(r);return e=Va.runKernel(ls,{x:e},a),t=Va.runKernel(ls,{x:t},a),n&&(t=Xu(t)),ii(e,t)})):Va.runKernel(ls,s,a)}}),Zu=ai({confusionMatrix_:function(e,t,n){const r=ti(e,"labels","confusionMatrix"),s=ti(t,"predictions","confusionMatrix");ie(null==n||n>0&&Number.isInteger(n),(()=>`If provided, numClasses must be a positive integer, but got ${n}`)),ie(1===r.rank,(()=>`Expected the rank of labels to be 1, but got ${r.rank}`)),ie(1===s.rank,(()=>`Expected the rank of predictions to be 1, but got ${s.rank}`)),ie(r.shape[0]===s.shape[0],(()=>`Mismatch in the number of examples: ${r.shape[0]} vs. ${s.shape[0]}. Labels and predictions should have the same number of elements.`)),ie(n>0&&Number.isInteger(n),(()=>`numClasses is required to be a positive integer, but got ${n}`));const a=qu(Lo(r,"int32"),n),i=qu(Lo(s,"int32"),n),o=Ju(a),u=Hu(o,i);return Lo(u,"int32")}});function Qu(e,t,n){if(ue(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const r=Za(e,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return oi(e,t,r,n)}var el=n(96763);let tl,nl=!1;function rl(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,s=!1,a=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&e instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)s=!0;else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)a=!0;else if(null!=e.getContext)i=!0;else{if(!("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap))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 ${e.constructor.name}`);o=!0}if(null!=Ts(gs,Va.backendName)){const n={pixels:e},r={numChannels:t};return Va.runKernel(gs,n,r)}const[u,l]=s?[e.videoWidth,e.videoHeight]:[e.width,e.height];let c,h;if(i)c=e.getContext("2d").getImageData(0,0,u,l).data;else if(r||n)c=e.data;else if(a||s||o){if(null==tl)if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas||"undefined"==typeof OffscreenCanvasRenderingContext2D)throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");tl=new OffscreenCanvas(1,1).getContext("2d")}else tl=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});tl.canvas.width=u,tl.canvas.height=l,tl.drawImage(e,0,0,u,l),c=tl.getImageData(0,0,u,l).data}if(4===t)h=new Int32Array(c);else{const e=u*l;h=new Int32Array(e*t);for(let n=0;n<e;n++)for(let e=0;e<t;++e)h[n*t+e]=c[4*n+e]}return Qu(h,[l,u,t],"int32")}async function sl(e,t=3){let n=null;if(Ye().getBool("WRAP_TO_IMAGEBITMAP")&&function(e){return"undefined"!=typeof window&&"undefined"!=typeof ImageBitmap&&window.hasOwnProperty("createImageBitmap")&&!(e instanceof ImageBitmap)&&function(e){return null!=e&&0!==e.width&&0!==e.height}(e)&&!function(e){return null!=e&&e.data instanceof Uint8Array}(e)}(e)){let t;try{t=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(e){t=null}n=null!=t&&t.width===e.width&&t.height===e.height?t:e}else n=e;return rl(n,t)}function al(e){if(2!==e.rank&&3!==e.rank)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${e.rank}.`);const t=2===e.rank?1:e.shape[2];if(t>4||2===t)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${t}`);if("float32"!==e.dtype&&"int32"!==e.dtype)throw new Error(`Unsupported type for toPixels: ${e.dtype}. Please use float32 or int32 tensors.`)}async function il(e,t){let n=ti(e,"img","toPixels");if(!(e instanceof wa)){const e=n;n=Lo(e,"int32"),e.dispose()}al(n);const[r,s]=n.shape.slice(0,2),a=2===n.rank?1:n.shape[2],i=await n.data(),o="float32"===n.dtype?255:1,u=new Uint8ClampedArray(s*r*4);for(let e=0;e<r*s;++e){const t=[0,0,0,255];for(let r=0;r<a;r++){const s=i[e*a+r];if("float32"===n.dtype){if(s<0||s>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${s}.`)}else if("int32"===n.dtype&&(s<0||s>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${s}.`);1===a?(t[0]=s*o,t[1]=s*o,t[2]=s*o):t[r]=s*o}const r=4*e;u[r+0]=Math.round(t[0]),u[r+1]=Math.round(t[1]),u[r+2]=Math.round(t[2]),u[r+3]=Math.round(t[3])}if(null!=t){nl||null!=Ts(Zt,Va.backendName)&&(el.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),nl=!0),t.width=s,t.height=r;const e=t.getContext("2d"),n=new ImageData(u,s,r);e.putImageData(n,0,0)}return n!==e&&n.dispose(),u}function ol(e,t,n){let r=ti(e,"img","draw");if(!(e instanceof wa)){const e=r;r=Lo(e,"int32"),e.dispose()}al(r),function(e){const t=(null==e?void 0:e.alpha)||1;if(t>1||t<0)throw new Error(`Alpha value ${t} is suppoed to be in range [0 - 1].`)}(null==n?void 0:n.imageOptions);const s={image:r},a={canvas:t,options:n};Va.runKernel(Zt,s,a)}const ul=ai({fromPixels_:rl});function ll(e,t){const n=e.shape.length,r=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(r<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${r}.`);if("int32"!==t.dtype)throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[r-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${n}`);if(0===le(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const s=t.shape,a=s[s.length-1];let i=1;for(let e=0;e<s.length-1;++e)i*=s[e];const o=e.shape,u=s.slice();u.pop();let l=1;for(let e=a;e<n;++e)l*=o[e],u.push(o[e]);const c=[...De(e.shape).map((e=>e/l)),1].slice(0,a);return[u,i,l,c]}function cl(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,s=t.rank>1?t.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${r}, and batchDim: ${s}.`;if(n.rank<s)throw new Error(a+` update.rank < ${s}. `);if(e.length<r+(n.rank-s))throw new Error(a+` Output shape length < ${r+(n.rank-s)}`);if(n.rank!==s+e.length-r)throw new Error(a+" update.rank != "+(s+e.length-r));for(let e=0;e<s;++e)if(n.shape[e]!==t.shape[e])throw new Error(a+` updates.shape[${e}] (${n.shape[e]}) != indices.shape[${e}] (${t.shape[e]}).`);for(let t=0;t<n.rank-s;++t)if(n.shape[t+s]!==e[t+r])throw new Error(a+` updates.shape[${t+s}] (${n.shape[t+s]}) != shape[${t+s}] (${e[t+s]})`)}function hl(e,t,n){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if("int32"!==t.dtype)throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(n.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);if(0===n.length){if(0===t.size)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(0===e.size)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}cl(n,t,e)}function pl(e,t,n){const r=t.shape.length,s=r>1?t.shape[r-1]:1,a=n.length;let i=1;for(let e=s;e<a;++e)i*=n[e];const o=s<1?1:s;return{sliceRank:s,numUpdates:le(t.shape)/o,sliceSize:i,strides:[...De(n.slice(0,s)),1],outputSize:le(n)}}const dl=-2,fl=-1;function ml(e,t,n){const r=e.shape.length;ie(r===t.length,(()=>`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`)),ie(r===n.length,(()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`));for(let s=0;s<r;++s)ie(t[s]+n[s]<=e.shape[s],(()=>`Error in slice${r}D: begin[${s}] + size[${s}] (${t[s]+n[s]}) would overflow input.shape[${s}] (${e.shape[s]})`))}function gl(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t}function yl(e,t,n){const r=[];for(let s=0;s<e.length;s++)r[s]=Math.ceil((t[s]-e[s])/n[s]);return r}function bl(e,t,n,r){const s=[...e];for(let e=s.length;e<r.length;e++)s.push(1);for(let e=0;e<n;e++)0===e?s[t]=1:(s.splice(t,0,1),s.pop());return s}function xl(e,t,n){return n<=e?n:n-(t-1)}function wl(e,t){const n=[];for(let r=0;r<e;r++)n.push(t+r);return n}function vl(e,t,n,r,s,a,i,o,u){const l=e.length;let c=new Array(l),h=new Array(l),p=new Array(l);if(t.length&&n>0){const u=t[0],l=n+1;c=kl(i,u,l,r,e),h=Il(o,u,l,s,e),p=bl(a,u,l,e)}else for(let t=0;t<l;t++)c[t]=Sl(i,r,a,e,t,u),h[t]=Tl(o,s,a,e,t,u),p[t]=Nl(a,t,u);return{begin:c,end:h,strides:p}}function kl(e,t,n,r,s){const a=[...s],i=wl(n,t);for(let s=0;s<a.length;s++)if(i.indexOf(s)>-1)a[s]=0;else{const i=xl(t,n,s);let o=r[i];e&1<<i&&(o=0),a[s]=o}return a}function Il(e,t,n,r,s){const a=[...s],i=wl(n,t);for(let s=0;s<a.length;s++)if(i.indexOf(s)>-1)a[s]=Number.MAX_SAFE_INTEGER;else{const i=xl(t,n,s);let o=r[i];e&1<<i&&(o=Number.MAX_SAFE_INTEGER),a[s]=o}for(let e=0;e<a.length;e++){const t=s[e];a[e]<0&&(a[e]+=t),a[e]=ee(0,a[e],s[e])}return a}function Nl(e,t,n){let r=e[t];return(n&1<<t||null==r)&&(r=1),r}function Sl(e,t,n,r,s,a){let i=t[s];const o=n[s]||1;(e&1<<s||a&1<<s||null==i)&&(i=o>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const u=r[s];return i<0&&(i+=u),i=ee(0,i,u-1),i}function Tl(e,t,n,r,s,a){let i=t[s];const o=n[s]||1;(e&1<<s||a&1<<s||null==i)&&(i=o>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const u=r[s];return i<0&&(i+=u),i=o>0?ee(0,i,u):ee(-1,i,u-1),i}function Cl(e,t,n){let r=n.length;for(let e=0;e<n.length;e++)if(n[e]>1){r=e;break}for(let s=r+1;s<n.length;s++)if(t[s]>0||n[s]!==e[s])return!1;return!0}function $l(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r<e.length-1;r++)n+=e[r]*t[r];return n}function El(e,t,n){let r;const s=e.shape.length;let a;return r="number"==typeof t?[t,...new Array(s-1).fill(0)]:t.length<s?t.concat(new Array(s-t.length).fill(0)):t.slice(),r.forEach((e=>{ie(-1!==e,(()=>"slice() does not support negative begin indexing."))})),a=null==n?new Array(s).fill(-1):"number"==typeof n?[n,...new Array(s-1).fill(-1)]:n.length<s?n.concat(new Array(s-n.length).fill(-1)):n,a=a.map(((t,n)=>t>=0?t:(ie(-1===t,(()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`)),e.shape[n]-r[n]))),[r,a]}function Al(e,t,n,r,s,a,i,o,u){let l;if(null==r?(l=new Array(t.length),l.fill(1)):l=r,null!=i&&i&i-1)throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const h={dims:l.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:l.slice(),beginMask:s,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:u};for(let e=0;e<h.dims;e++)c&&1<<e&o&&h.numAddAxisAfterEllipsis++,1<<e&i&&(c=!0);c||(h.ellipsisMask|=1<<h.dims,h.dims++);const p={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};!function(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let n=0;t.beginValid=null!=e.begin,t.endValid=null!=e.end,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let r=0;r<e.dims;r++)if(1<<r&e.ellipsisMask){const s=Math.min(t.dims-(e.dims-r)+1+e.numAddAxisAfterEllipsis,t.dims);for(;n<s;n++)t.begin[n]=0,t.end[n]=0,t.strides[n]=1,t.beginMask|=1<<n,t.endMask|=1<<n,t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[n]=r}else if(1<<r&e.newAxisMask)t.finalShapeGatherIndices.push(dl),t.finalShapeGatherIndicesSparse.push(-1);else{if(n===t.begin.length)throw Error(`Index out of range using input dim ${n}; input has only ${t.dims} dims, ${t.begin.length}.`);null!=e.begin&&(t.begin[n]=e.begin[r]),null!=e.end&&(t.end[n]=e.end[r]),t.strides[n]=e.strides[r],e.beginMask&1<<r&&(t.beginMask|=1<<n),e.endMask&1<<r&&(t.endMask|=1<<n),e.shrinkAxisMask&1<<r?(t.finalShapeGatherIndices.push(fl),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<n):(t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(r)),t.inputShapeGatherIndicesSparse[n]=r,n++}}(h,p);let d=!0,f=!0,m=!0;const g=[],y=[];for(let t=0;t<e.length;++t){if(0===p.strides[t])throw Error(`strides[${t}] must be non-zero`);const n=!!(p.shrinkAxisMask&1<<t),r=e[t];if(-1===r){g.push(n?1:-1);continue}const s=[p.beginMask&1<<t,p.endMask&1<<t],a=[p.strides[t]>0?0:-1,p.strides[t]>0?r:r-1];if(n&&p.strides[t]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&1===p.strides[t];const i=!!(p.beginMask&1<<t&&p.endMask&1<<t);if(p.beginValid&&p.endValid){if(n){const e=p.begin[t]<0?r+p.begin[t]:p.begin[t];if(p.begin[t]=e,p.end[t]=p.begin[t]+1,e<0||e>=r)throw Error(`slice index ${p.begin[t]} of dimension ${t} out of bounds.`)}else p.begin[t]=Rl(p.begin[t],0,p.strides[t],r,s,a),p.end[t]=Rl(p.end[t],1,p.strides[t],r,s,a);const e=1===p.strides[t]&&0===p.begin[t]&&p.end[t]===r;d=d&&e,f=f&&(0===t&&1===p.strides[t]||e)}else d=d&&1===p.strides[t]&&i,f=f&&(0===t&&1===p.strides[t]||i);let o,u=!1;if(p.beginValid&&p.endValid?(o=p.end[t]-p.begin[t],u=!0):n?(o=1,u=!0):i&&r>=0&&(o=p.strides[t]<0?-r:r,u=!0),u){let e;e=0===o||o<0!=p.strides[t]<0?0:Math.trunc(o/p.strides[t])+(o%p.strides[t]!=0?1:0),g.push(e)}else g.push(-1)}for(let e=0;e<p.finalShapeGatherIndices.length;++e){const t=p.finalShapeGatherIndices[e];t>=0?y.push(g[t]):t===dl&&y.push(1)}return{finalShapeSparse:y.filter(((e,t)=>p.finalShapeGatherIndices[t]!==dl)),finalShape:y,isIdentity:d,sliceDim0:f,isSimpleSlice:m,begin:p.begin,end:p.end,strides:p.strides}}function Rl(e,t,n,r,s,a){if(s[t])return n>0?a[t]:a[t+1&1];{const t=e<0?r+e:e;return t<a[0]?a[0]:t>a[1]?a[1]:t}}const Ol=.001,Fl=.1;function _l(e,t,n){return null==n&&(n=Dl()),Ml(e,t,((e,t)=>Bl(e,t,n)))}function Dl(){return 32===Va.backend.floatPrecision()?Ol:Fl}function Ml(e,t,n){let r=!0;if((na(e)||na(t))&&(r=!1),na(e)&&na(t)&&(r=!0),r){const n=e.constructor.name,r=t.constructor.name;if(n!==r)throw new Error(`Arrays are of different type. Actual: ${n}. Expected: ${r}`)}if(Array.isArray(e)&&Array.isArray(t)){const n=Za(e),r=Za(t);if(!pe(n,r))throw new Error(`Arrays have different shapes. Actual: [${n}]. Expected: [${r}]`)}const s=na(e)?e:ra(e),a=na(t)?t:ra(t);if(s.length!==a.length)throw new Error(`Arrays have different lengths actual: ${s.length} vs expected: ${a.length}.\nActual: ${s}.\nExpected: ${a}.`);for(let e=0;e<a.length;++e){const t=s[e],r=a[e];if(!n(t,r))throw new Error(`Arrays differ: actual[${e}] = ${t}, expected[${e}] = ${r}.\nActual: ${s}.\nExpected: ${a}.`)}"undefined"!=typeof expect&&expect().nothing()}function Ll(e,t){e().then((()=>t.fail()),(()=>t())),"undefined"!=typeof expect&&expect().nothing()}function zl(e,t){const n="string"==typeof t||"number"==typeof t||"boolean"==typeof t?[t]:t;return Ee(e)||Ee(e[0])||Ee(t)||Ee(t[0])?Ml(e,n,((e,t)=>e==t)):Ml(e,t,((e,t)=>Bl(e,t,0)))}function Pl(e,t,n){if(null==n&&(n=Dl()),!Bl(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);"undefined"!=typeof expect&&expect().nothing()}function Bl(e,t,n){return!isFinite(e)&&!isFinite(t)||!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function Wl(e,t,n){for(let r=0;r<e.length;r++)if(e[r]<t||e[r]>n)throw new Error(`Value out of range:${e[r]} low: ${t}, high: ${n}`)}function Ul(e,t){const n=new Float32Array(e),r=new Float32Array(t);if(n.length!==r.length)throw new Error(`Expected ArrayBuffer to be of length ${r.length}, but it was ${n.length}`);for(let e=0;e<r.length;e++)if(n[e]!==r[e])throw new Error(`Expected ArrayBuffer value at ${e} to be ${r[e]} but got ${n[e]} instead`)}function Vl(e){for(let t=0;t<e.length;t++){const n=e[t];Array.isArray(n)?Vl(n):e[t]=ea(n)}return e}function Gl(e){const t=document.createElement("video");return"playsInline"in t&&(t.playsInline=!0),t.muted=!0,t.loop=!0,t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.preload="auto",t.appendChild(e),new Promise((e=>{t.addEventListener("loadeddata",(n=>e(t))),t.load()}))}async function jl(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise((t=>{e.requestVideoFrameCallback(t)}))}const Hl="4.20.0";class ql{static sgd(e){return new vu(e)}static momentum(e,t,n=!1){return new ku(e,t,n)}static rmsprop(e,t=.9,n=0,r=null,s=!1){return new Iu(e,t,n,r,s)}static adam(e=.001,t=.9,n=.999,r=null){return new fu(e,t,n,r)}static adadelta(e=.001,t=.95,n=null){return new lu(e,t,n)}static adamax(e=.002,t=.9,n=.999,r=null,s=0){return new wu(e,t,n,r,s)}static adagrad(e,t=.1){return new hu(e,t)}}const Kl=ai({acos_:function(e){const t={x:ti(e,"x","acos")};return Va.runKernel(rt,t)}}),Xl=ai({acosh_:function(e){const t={x:ti(e,"x","acosh")};return Va.runKernel(st,t)}}),Yl=ai({addN_:function(e){ie(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),ie(e.length>=1,(()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`));const t=e.map(((e,t)=>ti(e,`tensors${t}`,"addN"))),n=t[0];t.forEach((e=>{if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")})),t.forEach((e=>{if(!pe(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const r=t;return Va.runKernel(it,r)}}),Jl=ai({all_:function(e,t=null,n=!1){const r={x:ti(e,"x","all","bool")},s={axis:t,keepDims:n};return Va.runKernel(ot,r,s)}}),Zl=ai({any_:function(e,t=null,n=!1){const r={x:ti(e,"x","any","bool")},s={axis:t,keepDims:n};return Va.runKernel(ut,r,s)}}),Ql=ai({argMax_:function(e,t=0){const n={x:ti(e,"x","argMax")},r={axis:t};return Va.runKernel(lt,n,r)}}),ec=ai({argMin_:function(e,t=0){const n={x:ti(e,"x","argMin")},r={axis:t};return Va.runKernel(ct,n,r)}}),tc=ai({asin_:function(e){const t={x:ti(e,"x","asin")};return Va.runKernel(ht,t)}}),nc=ai({asinh_:function(e){const t={x:ti(e,"x","asinh")};return Va.runKernel(pt,t)}}),rc=ai({atan_:function(e){const t={x:ti(e,"x","atan")};return Va.runKernel(dt,t)}}),sc=ai({atan2_:function(e,t){let n=ti(e,"a","atan2"),r=ti(t,"b","atan2");[n,r]=Fa(n,r);const s={a:n,b:r};return Va.runKernel(mt,s)}}),ac=ai({atanh_:function(e){const t={x:ti(e,"x","atanh")};return Va.runKernel(ft,t)}});function ic(e,t,n,r,s="NHWC",a){return lc(e,[...t,e[3]],n,a,r,null,null,xc(s))}function oc(e,t,n,r,s,a,i="channelsLast"){const[o,u]=pc(t);let l;if("channelsLast"===i)l=[o,u,e[3],e[3]];else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);l=[o,u,e[1],e[1]]}return lc(e,l,n,r,s,a,!1,i)}function uc(e,t,n,r,s,a,i="NDHWC"){const[o,u,l]=dc(t);let c,h;if("NDHWC"===i)h="channelsLast",c=[o,u,l,e[4],e[4]];else{if("NCDHW"!==i)throw new Error(`Unknown dataFormat ${i}`);h="channelsFirst",c=[o,u,l,e[1],e[1]]}return cc(e,c,n,r,s,!1,h,a)}function lc(e,t,n,r,s,a,i=!1,o="channelsLast"){let[u,l,c,h]=[-1,-1,-1,-1];if("channelsLast"===o)[u,l,c,h]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[u,h,l,c]=e}const[p,d,,f]=t,[m,g]=pc(n),[y,b]=pc(r),x=fc(p,y),w=fc(d,b),{padInfo:v,outHeight:k,outWidth:I}=function(e,t,n,r,s,a,i,o,u){let l,c,h;if("number"==typeof e){l={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const s=function(e,t,n,r,s){null==r&&(r=hc(e,t,n));const a=e[1];return[mc((e[0]-t+2*r)/n+1,s),mc((a-t+2*r)/n+1,s)]}([t,n],a,r,e,o);c=s[0],h=s[1]}else if("same"===e){c=Math.ceil(t/r),h=Math.ceil(n/s);const e=Math.max(0,(c-1)*r+a-t),o=Math.max(0,(h-1)*s+i-n),u=Math.floor(e/2),p=e-u,d=Math.floor(o/2);l={top:u,bottom:p,left:d,right:o-d,type:"SAME"}}else if("valid"===e)l={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-a+1)/r),h=Math.ceil((n-i+1)/s);else{if("object"!=typeof e)throw Error(`Unknown padding parameter: ${e}`);{const p="channelsLast"===u?e[1][0]:e[2][0],d="channelsLast"===u?e[1][1]:e[2][1],f="channelsLast"===u?e[2][0]:e[3][0],m="channelsLast"===u?e[2][1]:e[3][1];l={top:p,bottom:d,left:f,right:m,type:0===p&&0===d&&0===f&&0===m?"VALID":"EXPLICIT"},c=mc((t-a+p+d)/r+1,o),h=mc((n-i+f+m)/s+1,o)}}return{padInfo:l,outHeight:c,outWidth:h}}(s,l,c,m,g,x,w,a,o),N=i?f*h:f;let S;return"channelsFirst"===o?S=[u,N,k,I]:"channelsLast"===o&&(S=[u,k,I,N]),{batchSize:u,dataFormat:o,inHeight:l,inWidth:c,inChannels:h,outHeight:k,outWidth:I,outChannels:N,padInfo:v,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:d,effectiveFilterHeight:x,effectiveFilterWidth:w,dilationHeight:y,dilationWidth:b,inShape:e,outShape:S,filterShape:t}}function cc(e,t,n,r,s,a=!1,i="channelsLast",o){let[u,l,c,h,p]=[-1,-1,-1,-1,-1];if("channelsLast"===i)[u,l,c,h,p]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[u,p,l,c,h]=e}const[d,f,m,,g]=t,[y,b,x]=dc(n),[w,v,k]=dc(r),I=fc(d,w),N=fc(f,v),S=fc(m,k),{padInfo:T,outDepth:C,outHeight:$,outWidth:E}=function(e,t,n,r,s,a,i,o,u,l,c){let h,p,d,f;if("valid"===e&&(e=0),"number"==typeof e){h={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const m=function(e,t,n,r,s,a){null==s&&(s=hc(e,t[0],r[0]));const i=[0,0,0,1];for(let n=0;n<3;n++)e[n]+2*s>=t[n]&&(i[n]=mc((e[n]-t[n]+2*s)/r[n]+1,a));return i}([t,n,r,1],[o,u,l],0,[s,a,i],e,c);p=m[0],d=m[1],f=m[2]}else{if("same"!==e)throw Error(`Unknown padding parameter: ${e}`);{p=Math.ceil(t/s),d=Math.ceil(n/a),f=Math.ceil(r/i);const e=(p-1)*s+o-t,c=(d-1)*a+u-n,m=(f-1)*i+l-r,g=Math.floor(e/2),y=e-g,b=Math.floor(c/2),x=c-b,w=Math.floor(m/2);h={top:b,bottom:x,left:w,right:m-w,front:g,back:y,type:"SAME"}}}return{padInfo:h,outDepth:p,outHeight:d,outWidth:f}}(s,l,c,h,y,b,x,I,N,S,o),A=a?g*p:g;let R;return"channelsFirst"===i?R=[u,A,C,$,E]:"channelsLast"===i&&(R=[u,C,$,E,A]),{batchSize:u,dataFormat:i,inDepth:l,inHeight:c,inWidth:h,inChannels:p,outDepth:C,outHeight:$,outWidth:E,outChannels:A,padInfo:T,strideDepth:y,strideHeight:b,strideWidth:x,filterDepth:d,filterHeight:f,filterWidth:m,effectiveFilterDepth:I,effectiveFilterHeight:N,effectiveFilterWidth:S,dilationDepth:w,dilationHeight:v,dilationWidth:k,inShape:e,outShape:R,filterShape:t}}function hc(e,t,n,r=1){const s=fc(t,r);return Math.floor((e[0]*(n-1)-n+s)/2)}function pc(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function dc(e){return"number"==typeof e?[e,e,e]:e}function fc(e,t){return t<=1?e:e+(e-1)*(t-1)}function mc(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function gc(e){const[t,n,r]=pc(e);return 1===t&&1===n&&1===r}function yc(e,t){return gc(e)||gc(t)}function bc(e){return pc(e).every((e=>e>0))}function xc(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function wc(e,t,n){if(null!=n){if("string"==typeof t)throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if("number"==typeof t)ie(de(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`));else{if("object"!=typeof t)throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);t.forEach((t=>{t.forEach((t=>{ie(de(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}const vc=ai({reshape_:function(e,t){const n={x:ti(e,"x","reshape","string_or_numeric")},r={shape:t};return Va.runKernel(wr,n,r)}}),kc=ai({avgPool_:function(e,t,n,r,s){const a=ti(e,"x","avgPool","float32");ie(yc(n,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`));let i=a,o=!1;3===a.rank&&(o=!0,i=vc(a,[1,a.shape[0],a.shape[1],a.shape[2]])),ie(4===i.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`)),wc("avgPool",r,s);const u={x:i},l={filterSize:t,strides:n,pad:r,dimRoundingMode:s};let c=Va.runKernel(gt,u,l);return c=Lo(c,a.dtype),o?vc(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),Ic=ai({avgPool3d_:function(e,t,n,r,s,a="NDHWC"){const i=ti(e,"x","avgPool3d","float32");let o=i,u=!1;4===i.rank&&(u=!0,o=vc(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),ie(5===o.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`)),ie("NDHWC"===a,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`)),ie("number"==typeof n&&n>0||Array.isArray(n)&&n[0]>0&&n[1]>0&&n[2]>0,(()=>`Error in avgPool3d: Stride must be > 0, but got '${n}'`)),wc("avgPool3d",r,s);const l={x:o},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a};let h=Va.runKernel(bt,l,c);return h=Lo(h,o.dtype),u?vc(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),Nc=ai({concat_:function(e,t=0){ie(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=ni(e,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach((e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${e.dtype}. `)})),1===n.length)return zo(n[0]);const r=n,s={axis:t};return Va.runKernel(Rt,r,s)}}),Sc=ai({sigmoid_:function(e){const t={x:ti(e,"x","sigmoid","float32")};return Va.runKernel(zr,t)}}),Tc=ai({slice_:function(e,t,n){const r=ti(e,"x","slice","string_or_numeric");if(0===r.rank)throw new Error("Slicing scalar is not possible");const s={x:r},a={begin:t,size:n};return Va.runKernel(_r,s,a)}}),Cc=ai({tanh_:function(e){const t={x:ti(e,"x","tanh","float32")};return Va.runKernel(as,t)}}),$c=ai({basicLSTMCell_:function(e,t,n,r,s,a){const i=ti(e,"forgetBias","basicLSTMCell"),o=ti(t,"lstmKernel","basicLSTMCell"),u=ti(n,"lstmBias","basicLSTMCell"),l=ti(r,"data","basicLSTMCell"),c=ti(s,"c","basicLSTMCell"),h=ti(a,"h","basicLSTMCell"),p=Nc([l,h],1),d=Hu(p,o),f=Wo(d,u),m=f.shape[0],g=f.shape[1]/4,y=[m,g],b=Tc(f,[0,0],y),x=Tc(f,[0,g],y),w=Tc(f,[0,2*g],y),v=Tc(f,[0,3*g],y),k=Wo(Go(Sc(b),Cc(x)),Go(c,Sc(Wo(i,w))));return[k,Go(Cc(k),Sc(v))]}}),Ec=ai({batchToSpaceND_:function(e,t,n){const r=ti(e,"x","batchToSpaceND"),s=t.reduce(((e,t)=>e*t));ie(r.rank>=1+t.length,(()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`)),ie(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`)),ie(r.shape[0]%s==0,(()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${s}`));const a={x:r},i={blockShape:t,crops:n};return Va.runKernel(vt,a,i)}}),Ac=ai({batchNorm_:function(e,t,n,r,s,a){null==a&&(a=.001);const i=ti(e,"x","batchNorm"),o=ti(t,"mean","batchNorm"),u=ti(n,"variance","batchNorm");let l,c;null!=s&&(l=ti(s,"scale","batchNorm")),null!=r&&(c=ti(r,"offset","batchNorm")),ie(o.rank===u.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),ie(null==c||o.rank===c.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),ie(null==l||o.rank===l.rank,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));const h={x:function(e){let t;return t=0===e.rank||1===e.rank?vc(e,[1,1,1,e.size]):2===e.rank?vc(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?vc(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(i),scale:l,offset:c,mean:o,variance:u},p={varianceEpsilon:a},d=Va.runKernel(fn,h,p);return vc(d,i.shape)}}),Rc=ai({batchNorm2d_:function(e,t,n,r,s,a){const i=ti(e,"x","batchNorm"),o=ti(t,"mean","batchNorm"),u=ti(n,"variance","batchNorm");let l,c;return null!=s&&(l=ti(s,"scale","batchNorm")),null!=r&&(c=ti(r,"offset","batchNorm")),ie(2===i.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`)),ie(2===o.rank||1===o.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`)),ie(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`)),null!=l&&ie(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${l.rank}.`)),null!=c&&ie(2===c.rank||1===c.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`)),Ac(i,o,u,c,l,a)}}),Oc=ai({batchNorm3d_:function(e,t,n,r,s,a){const i=ti(e,"x","batchNorm"),o=ti(t,"mean","batchNorm"),u=ti(n,"variance","batchNorm");let l,c;return null!=s&&(l=ti(s,"scale","batchNorm")),null!=r&&(c=ti(r,"offset","batchNorm")),ie(3===i.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`)),ie(3===o.rank||1===o.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`)),ie(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${u.rank}.`)),null!=l&&ie(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${l.rank}.`)),null!=c&&ie(3===c.rank||1===c.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`)),Ac(i,o,u,c,l,a)}}),Fc=ai({batchNorm4d_:function(e,t,n,r,s,a){const i=ti(e,"x","batchNorm"),o=ti(t,"mean","batchNorm"),u=ti(n,"variance","batchNorm");let l,c;return null!=s&&(l=ti(s,"scale","batchNorm")),null!=r&&(c=ti(r,"offset","batchNorm")),ie(4===i.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`)),ie(4===o.rank||1===o.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`)),ie(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${u.rank}.`)),null!=l&&ie(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${l.rank}.`)),null!=c&&ie(4===c.rank||1===c.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`)),Ac(i,o,u,c,l,a)}}),_c=ai({bincount_:function(e,t,n){const r=ti(e,"x","bincount"),s=ti(t,"weights","bincount");ie("int32"===r.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`)),ie(n>=0,(()=>`size must be non-negative, but got ${n}.`)),ie(s.size===r.size||0===s.size,(()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${r.shape}, weights shape: ${s.shape}.`));const a={x:r,weights:s},i={size:n};return Va.runKernel(kt,a,i)}}),Dc=ai({bitwiseAnd_:function(e,t){const n=ti(e,"x","bitwiseAnd"),r=ti(t,"y","bitwiseAnd");if(!pe(n.shape,r.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${n.shape}, y: ${r.shape}`);if("int32"!==n.dtype||"int32"!==r.dtype)throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${n.dtype} and type of y: ${r.dtype}`);const s={a:n,b:r};return Va.runKernel(It,s)}}),Mc=ai({broadcastArgs_:function(e,t){const n=ti(e,"s0","broadcastArgs","int32"),r=ti(t,"s1","broadcastArgs","int32");if(1!==n.rank)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(1!==r.rank)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${r.rank}`);const s={s0:n,s1:r};return Va.runKernel(St,s)}}),Lc=ai({broadcastTo_:function(e,t){let n=ti(e,"broadcastTo","x");const r=n.shape;if(Ue(t),t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){const e=n.shape.slice();for(;e.length<t.length;)e.unshift(1);n=vc(n,e)}const s=n.shape,a=Array.from(t);for(let e=t.length-1;e>=0;e--)if(s[e]===t[e])a[e]=1;else if(1!==n.shape[e])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);if(0===a.map(((e,t)=>e>1?t:-1)).filter((e=>e>=0)).length)return zo(n);const i={x:n},o={reps:a};return Va.runKernel(is,i,o)}}),zc=ai({ceil_:function(e){const t={x:ti(e,"x","ceil","float32")};return Va.runKernel(Ct,t)}}),Pc=ai({clipByValue_:function(e,t,n){const r=ti(e,"x","clipByValue");if(ie(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`)),t===n)return cu(r.shape,t,r.dtype);const s={x:r},a={clipValueMin:t,clipValueMax:n};return Va.runKernel($t,s,a)}}),Bc=ai({concat1d_:function(e){return Nc(e,0)}}),Wc=ai({concat2d_:function(e,t){return Nc(e,t)}}),Uc=ai({concat3d_:function(e,t){return Nc(e,t)}}),Vc=ai({concat4d_:function(e,t){return Nc(e,t)}}),Gc=ai({conv2d_:function(e,t,n,r,s="NHWC",a=[1,1],i){const o=ti(e,"x","conv2d","float32"),u=ti(t,"filter","conv2d","float32");let l=o,c=!1;3===o.rank&&(c=!0,l=vc(o,[1,o.shape[0],o.shape[1],o.shape[2]])),ie(4===l.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${l.rank}.`)),ie(4===u.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${u.rank}.`)),wc("conv2d",r,i);const h="NHWC"===s?l.shape[3]:l.shape[1];ie(h===u.shape[2],(()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${u.shape[2]}.`)),ie(yc(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),ie(bc(a),(()=>"Error in conv2D: Dilated rates should be larger than 0.")),ie(bc(n),(()=>"Error in conv2D: Strides should be larger than 0."));const p={x:l,filter:u},d={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i},f=Va.runKernel(Ot,p,d);return c?vc(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),jc=ai({conv1d_:function(e,t,n,r,s="NWC",a=1,i){const o=ti(e,"x","conv1d"),u=ti(t,"filter","conv1d");let l=o,c=!1;2===o.rank&&(c=!0,l=vc(o,[1,o.shape[0],o.shape[1]])),ie(3===l.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${l.rank}.`)),ie(3===u.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${u.rank}.`)),wc("conv1d",r,i),ie(l.shape[2]===u.shape[1],(()=>`Error in conv1d: depth of input (${l.shape[2]}) must match input depth for filter ${u.shape[1]}.`)),ie(yc(n,a),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`)),ie(bc(a),(()=>"Error in conv1D: Dilated rates should be larger than 0.")),ie(bc(n),(()=>"Error in conv1D: Stride should be larger than 0.")),ie("NWC"===s,(()=>`Error in conv1d: got dataFormat of ${s} but only NWC is currently supported.`));const h=vc(u,[1,u.shape[0],u.shape[1],u.shape[2]]),p=vc(l,[l.shape[0],1,l.shape[1],l.shape[2]]),d=Gc(p,h,[1,n],r,"NHWC",[1,a],i);return vc(d,c?[d.shape[2],d.shape[3]]:[d.shape[0],d.shape[2],d.shape[3]])}}),Hc=ai({conv2DBackpropInput_:function(e,t,n,r,s,a="NHWC",i){ie(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let o=e,u=t,l=!1;3===t.rank&&(l=!0,u=vc(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),ie(4===o.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`)),ie(4===u.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${u.rank}`)),ie(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const c="NHWC"===a?o[3]:o[1],h="NHWC"===a?u.shape[3]:u.shape[1];ie(c===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[2]}.`)),ie(h===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${n.shape[3]}.`)),wc("conv2dDerInput",s,i);const p={dy:u,filter:n},d={strides:r,pad:s,dataFormat:a,dimRoundingMode:i,inputShape:o},f=Va.runKernel(_t,p,d);return l?vc(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),qc=ai({conv2dTranspose_:function(e,t,n,r,s,a){const i=ti(e,"x","conv2dTranspose"),o=ti(t,"filter","conv2dTranspose");return Hc(n,i,o,r,s,"NHWC",a)}}),Kc=ai({conv3d_:function(e,t,n,r,s="NDHWC",a=[1,1,1]){const i=ti(e,"x","conv3d"),o=ti(t,"filter","conv3d");let u=i,l=!1;4===i.rank&&(l=!0,u=vc(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),ie(5===u.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${u.rank}.`)),ie(5===o.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`)),ie(u.shape[4]===o.shape[3],(()=>`Error in conv3d: depth of input (${u.shape[4]}) must match input depth for filter ${o.shape[3]}.`)),ie(yc(n,a),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),ie("NDHWC"===s,(()=>`Error in conv3d: got dataFormat of ${s} but only NDHWC is currently supported.`)),ie(bc(a),(()=>"Error in conv3D: Dilated rates should be larger than 0.")),ie(bc(n),(()=>"Error in conv3D: Strides should be larger than 0."));const c={x:u,filter:o},h={strides:n,pad:r,dataFormat:s,dilations:a},p=Va.runKernel(Dt,c,h);return l?vc(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),Xc=ai({conv3DBackpropInput_:function(e,t,n,r,s){ie(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let a=e,i=t,o=!1;4===t.rank&&(o=!0,i=vc(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);const u=a[4],l=i.shape[4];ie(5===a.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`)),ie(5===i.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`)),ie(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),ie(u===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[3]}.`)),ie(l===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${l}) must match output depth for filter ${n.shape[4]}.`));const c={dy:i,filter:n},h={pad:s,strides:r,inputShape:a},p=Va.runKernel(Lt,c,h);return o?vc(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),Yc=ai({conv3dTranspose_:function(e,t,n,r,s){const a=ti(e,"x","conv3dTranspose"),i=ti(t,"filter","conv3dTranspose");return Xc(n,a,i,r,s)}}),Jc=ai({cos_:function(e){const t={x:ti(e,"x","cos","float32")};return Va.runKernel(zt,t)}}),Zc=ai({cosh_:function(e){const t={x:ti(e,"x","cosh","float32")};return Va.runKernel(Pt,t)}}),Qc=ai({cumprod_:function(e,t=0,n=!1,r=!1){const s={x:ti(e,"x","cumprod")},a={axis:t,exclusive:n,reverse:r};return Va.runKernel(Bt,s,a)}}),eh=ai({cumsum_:function(e,t=0,n=!1,r=!1){const s={x:ti(e,"x","cumsum")},a={axis:t,exclusive:n,reverse:r};return Va.runKernel(Wt,s,a)}}),th=ai({denseBincount_:function(e,t,n,r=!1){const s=ti(e,"x","denseBincount"),a=ti(t,"weights","denseBincount");ie("int32"===s.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${s.dtype}`)),ie(s.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${s.rank}.`)),ie(n>=0,(()=>`size must be non-negative, but got ${n}.`)),ie(a.size===s.size||0===a.size,(()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${s.shape}, weights shape: ${a.shape}.`));const i={x:s,weights:a},o={size:n,binaryOutput:r};return Va.runKernel(Vt,i,o)}}),nh=ai({depthToSpace_:function(e,t,n="NHWC"){const r=ti(e,"x","depthToSpace","float32"),s="NHWC"===n?r.shape[1]:r.shape[2],a="NHWC"===n?r.shape[2]:r.shape[3],i="NHWC"===n?r.shape[3]:r.shape[1];ie(t>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`)),ie(s*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${s} and ${t} for depthToSpace with input shape\n ${r.shape}`)),ie(a*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${r.shape}`)),ie(i%(t*t)==0,(()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${r.shape}`));const o={x:r},u={blockSize:t,dataFormat:n};return Va.runKernel(Gt,o,u)}}),rh=ai({depthwiseConv2d_:function(e,t,n,r,s="NHWC",a=[1,1],i){const o=ti(e,"x","depthwiseConv2d","float32"),u=ti(t,"filter","depthwiseConv2d","float32");let l=o,c=!1;3===o.rank&&(c=!0,l=vc(o,[1,o.shape[0],o.shape[1],o.shape[2]])),ie(4===l.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${l.rank}.`)),ie(4===u.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`));const h="NHWC"===s?l.shape[3]:l.shape[1];ie(h===u.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${h}) must match the inChannels dimension in filter ${u.shape[2]}.`)),wc("depthwiseConv2d",r,i);const p={x:l,filter:u},d={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i},f=Va.runKernel(jt,p,d);return c?vc(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),sh=ai({diag_:function(e){const t={x:ti(e,"x","diag")};return Va.runKernel(Kt,t)}}),ah=ai({dilation2d_:function(e,t,n,r,s=[1,1],a="NHWC"){const i=ti(e,"x","dilation2d"),o=ti(t,"filter","dilation2d");ie(3===i.rank||4===i.rank,(()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`)),ie(3===o.rank,(()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`)),ie("NHWC"===a,(()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`));let u=i,l=!1;3===i.rank&&(u=vc(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=!0),ie(u.shape[3]===o.shape[2],(()=>`Error in dilation2d: input and filter must have the same depth: ${u.shape[3]} vs ${o.shape[2]}`));const c={x:u,filter:o},h={strides:n,pad:r,dilations:s},p=Va.runKernel(Xt,c,h);return l?vc(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),ih=ai({equal_:function(e,t){let n=ti(e,"a","equal","string_or_numeric"),r=ti(t,"b","equal","string_or_numeric");[n,r]=Fa(n,r),bu(n.shape,r.shape);const s={a:n,b:r};return Va.runKernel(sn,s)}}),oh=ai({where_:function(e,t,n){const r=ti(t,"a","where"),s=ti(n,"b","where"),a=ti(e,"condition","where","bool"),i=bu(bu(a.shape,r.shape),s.shape),o={condition:Lc(a,i),t:Lc(r,i),e:Lc(s,i)};return Va.runKernel(Or,o)}}),uh=ai({divNoNan_:function(e,t){let n=ti(e,"a","div"),r=ti(t,"b","div");[n,r]=Fa(n,r);const s=Vo(n,r),a=qo(s),i=ih(r,a);return oh(i,a,s)}}),lh=ai({dot_:function(e,t){const n=ti(e,"t1","dot"),r=ti(t,"t2","dot");ie(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),(()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`));const s=1===n.rank?n.size:n.shape[1],a=1===r.rank?r.size:r.shape[0];if(ie(s===a,(()=>`Error in dot: inner dimensions of inputs must match, but got ${s} and ${a}.`)),1===n.rank&&1===r.rank){const e=vc(n,[1,-1]),t=vc(r,[-1,1]),s=Hu(e,t);return vc(s,[])}if(1===n.rank&&2===r.rank){const e=vc(n,[1,-1]),t=vc(r,[r.shape[0],r.shape[1]]),s=Hu(e,t);return vc(s,[s.size])}if(2===n.rank&&1===r.rank){const e=vc(r,[-1,1]),t=Hu(n,e);return vc(t,[t.size])}{const e=vc(r,[r.shape[0],r.shape[1]]);return Hu(n,e)}}}),ch=ai({einsum_:function(e,...t){const n=t.map(((e,t)=>ti(e,`tensors${t}`,"einsum"))),r={equation:e};return Va.runKernel(en,n,r)}}),hh=ai({elu_:function(e){const t={x:ti(e,"x","elu","float32")};return Va.runKernel(tn,t)}}),ph=ai({ensureShape_:function(e,t){const n=ti(e,"x","ensureShape","string_or_numeric");if(!he(n.shape,t))throw new Error(`EnsureShape: Shape of tensor ${n.shape} is not compatible with expected shape ${t}`);return e}}),dh=ai({erf_:function(e){let t=ti(e,"x","erf");ie("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=Lo(t,"float32"));const n={x:t};return Va.runKernel(rn,n)}});function fh(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function mh(e,t,n){const r=e.length+t.length,s=[];let a=0,i=0;for(let o=0;o<r;o++)-1===n.indexOf(o)?s.push(e[a++]):s.push(t[i++]);return s}function gh(e,t){const n=[],r=e.length;for(let s=0;s<r;s++)-1===t.indexOf(s)&&n.push(e[s]);return[n,t.map((t=>e[t]))]}function yh(e,t){return mh(e,t.map((e=>1)),t)}function bh(e,t,n){ie(fh(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}function xh(e,t){if(fh(e,t))return null;const n=[];for(let r=0;r<t;++r)-1===e.indexOf(r)&&n.push(r);return e.forEach((e=>n.push(e))),n}function wh(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))}function vh(e,t){const n=[];for(let r=t-e;r<t;++r)n.push(r);return n}const kh=ai({max_:function(e,t=null,n=!1){const r={x:ti(e,"x","max")},s={reductionIndices:t,keepDims:n};return Va.runKernel(Bn,r,s)}}),Ih=ai({min_:function(e,t=null,n=!1){const r={x:ti(e,"x","min")},s={axis:t,keepDims:n};return Va.runKernel(Kn,r,s)}}),Nh=ai({sum_:function(e,t=null,n=!1){let r=ti(e,"x","sum");"bool"===r.dtype&&(r=Lo(r,"int32"));const s={x:r},a={axis:t,keepDims:n};return Va.runKernel(Wr,s,a)}});function Sh(e,t,n=null){if(0===e.rank)return mu(e);if(1!==e.rank&&null===n)return Sh(vc(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return Nh(mu(e),n);if(t===1/0)return kh(mu(e),n);if(t===-1/0)return Ih(mu(e),n);if("euclidean"===t||2===t)return jo(Nh(pu(mu(e),tu(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return kh(Nh(mu(e),n[0]),n[1]-1);if(t===1/0)return kh(Nh(mu(e),n[1]),n[0]);if(t===-1/0)return Ih(Nh(mu(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return jo(Nh(Ho(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Th=ai({norm_:function(e,t="euclidean",n=null,r=!1){const s=Sh(e=ti(e,"x","norm"),t,n);let a=s.shape;if(r){const t=we(n,e.shape);a=yh(s.shape,t)}return vc(s,a)}}),Ch=ai({euclideanNorm_:function(e,t=null,n=!1){return Th(e,"euclidean",t,n)}}),$h=ai({exp_:function(e){const t={x:ti(e,"x","exp")};return Va.runKernel(an,t)}}),Eh=ai({expandDims_:function(e,t=0){const n=ti(e,"x","expandDims","string_or_numeric");ie(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const r={input:n},s={dim:t};return Va.runKernel(on,r,s)}}),Ah=ai({expm1_:function(e){const t={x:ti(e,"x","expm1")};return Va.runKernel(un,t)}}),Rh=ai({tile_:function(e,t){const n=ti(e,"x","tile","string_or_numeric");ie(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`));const r={x:n},s={reps:t};return Va.runKernel(is,r,s)}}),Oh=ai({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const s=Mo([e,t],r),a=e<=t?e:t;for(let e=0;e<a;++e)s.set(1,e,e);const i=vc(s.toTensor(),[e,t]);if(null==n)return i;if(1===n.length)return Rh(Eh(i,0),[n[0],1,1]);if(2===n.length)return Rh(Eh(Eh(i,0),0),[n[0],n[1],1,1]);if(3===n.length)return Rh(Eh(Eh(Eh(i,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}}),Fh=ai({floor_:function(e){const t={x:ti(e,"x","floor","float32")};return Va.runKernel(pn,t)}}),_h=ai({gather_:function(e,t,n=0,r=0){const s={x:ti(e,"x","gather"),indices:ti(t,"indices","gather","int32")},a={axis:n,batchDims:r};return Va.runKernel(mn,s,a)}}),Dh=ai({greater_:function(e,t){let n=ti(e,"a","greater","string_or_numeric"),r=ti(t,"b","greater","string_or_numeric");[n,r]=Fa(n,r),bu(n.shape,r.shape);const s={a:n,b:r};return Va.runKernel(yn,s)}}),Mh=ai({greaterEqual_:function(e,t){let n=ti(e,"a","greaterEqual","string_or_numeric"),r=ti(t,"b","greaterEqual","string_or_numeric");[n,r]=Fa(n,r),bu(n.shape,r.shape);const s={a:n,b:r};return Va.runKernel(bn,s)}}),Lh=ai({isFinite_:function(e){const t={x:ti(e,"x","isFinite")};return Va.runKernel(kn,t)}}),zh=ai({isInf_:function(e){const t={x:ti(e,"x","isInf")};return Va.runKernel(In,t)}}),Ph=ai({isNaN_:function(e){const t={x:ti(e,"x","isNaN")};return Va.runKernel(Nn,t)}}),Bh=ai({leakyRelu_:function(e,t=.2){const n={x:ti(e,"x","leakyRelu")},r={alpha:t};return Va.runKernel(Sn,n,r)}}),Wh=ai({less_:function(e,t){let n=ti(e,"a","less","string_or_numeric"),r=ti(t,"b","less","string_or_numeric");[n,r]=Fa(n,r),bu(n.shape,r.shape);const s={a:n,b:r};return Va.runKernel(Tn,s)}}),Uh=ai({lessEqual_:function(e,t){let n=ti(e,"a","lessEqual","string_or_numeric"),r=ti(t,"b","lessEqual","string_or_numeric");[n,r]=Fa(n,r),bu(n.shape,r.shape);const s={a:n,b:r};return Va.runKernel(Cn,s)}});function Vh(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const r={start:e,stop:t,num:n};return Va.runKernel($n,{},r)}const Gh=ai({localResponseNormalization_:function(e,t=5,n=1,r=1,s=.5){const a=ti(e,"x","localResponseNormalization");ie(4===a.rank||3===a.rank,(()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${a.rank}.`)),ie(de(t),(()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`));let i=a,o=!1;3===a.rank&&(o=!0,i=vc(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const u={x:i},l={depthRadius:t,bias:n,alpha:r,beta:s},c=Va.runKernel(Ln,u,l);return o?vc(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),jh=ai({log_:function(e){const t={x:ti(e,"x","log","float32")};return Va.runKernel(En,t)}}),Hh=ai({log1p_:function(e){const t={x:ti(e,"x","log1p")};return Va.runKernel(An,t)}}),qh=ai({softplus_:function(e){const t={x:ti(e,"x","softplus")};return Va.runKernel(Pr,t)}}),Kh=ai({logSigmoid_:function(e){const t=ti(e,"x","logSigmoid");return Qo((e=>({value:Xu(qh(Xu(e))),gradFunc:t=>Go(t,Sc(Xu(e)))})))(t)}}),Xh=ai({logSoftmax_:function(e,t=-1){const n=ti(e,"logits","logSoftmax");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);const r=Qo(((e,n)=>{const r=kh(e,t,!0),s=du(e,r),a=du(Lo(s,"float32"),jh(Nh($h(s),t,!0)));return n([a]),{value:a,gradFunc:(e,n)=>{const[r]=n,s=$h(r);return du(e,Go(Nh(e,t,!0),s))}}}));return r(n)}}),Yh=ai({logSumExp_:function(e,t=null,n=!1){const r=ti(e,"x","logSumExp"),s=we(t,r.shape),a=kh(r,s,!0),i=du(r,a),o=$h(i),u=Nh(o,s),l=jh(u),c=Wo(vc(a,l.shape),l);if(n){const e=yh(c.shape,s);return vc(c,e)}return c}}),Jh=ai({logicalAnd_:function(e,t){const n=ti(e,"a","logicalAnd","bool"),r=ti(t,"b","logicalAnd","bool");bu(n.shape,r.shape);const s={a:n,b:r};return Va.runKernel(Rn,s)}}),Zh=ai({logicalNot_:function(e){const t={x:ti(e,"x","logicalNot","bool")};return Va.runKernel(On,t)}}),Qh=ai({logicalOr_:function(e,t){const n=ti(e,"a","logicalOr","bool"),r=ti(t,"b","logicalOr","bool");bu(n.shape,r.shape);const s={a:n,b:r};return Va.runKernel(Fn,s)}}),ep=ai({logicalXor_:function(e,t){const n=ti(e,"a","logicalXor","bool"),r=ti(t,"b","logicalXor","bool");return bu(n.shape,r.shape),Jh(Qh(e,t),Zh(Jh(e,t)))}}),tp=2147483648,np=ai({searchSorted_:function(e,t,n="left"){const r=ti(e,"sortedSequence","searchSorted"),s=ti(t,"values","searchSorted"),a=r.shape[r.shape.length-1],i=s.shape[s.shape.length-1],o=vc(r,[-1,a]),u=vc(s,[-1,i]);if(o.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(o.shape[0]!==u.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(le(u.shape)>=tp)throw new Error("values tensor size must less than 2147483648");if(o.shape[1]>=tp)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${o.shape[1]}`);const l={sortedSequence:o,values:u},c={side:n};return Va.runKernel(Rr,l,c)}});function rp(e,t){return np(e,t,"left")}const sp=ai({maxPool_:function(e,t,n,r,s){const a=ti(e,"x","maxPool");let i=a,o=!1;3===a.rank&&(o=!0,i=vc(a,[1,a.shape[0],a.shape[1],a.shape[2]])),ie(4===i.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`)),ie(yc(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),wc("maxPool",r,s);const u={x:i},l={filterSize:t,strides:n,pad:r,dimRoundingMode:s},c=Va.runKernel(Un,u,l);return o?vc(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),ap=ai({maxPool3d_:function(e,t=[1,1,1],n,r,s,a="NDHWC"){const i=ti(e,"x","maxPool3d");let o=i,u=!1;4===i.rank&&(u=!0,o=vc(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),ie(5===o.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`)),ie("NDHWC"===a,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`)),wc("maxPool3d",r,s);const l={x:o},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},h=Va.runKernel(Gn,l,c);return u?vc(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),ip=ai({maxPoolWithArgmax_:function(e,t,n,r,s=!1){const a={x:ti(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:r,includeBatchInIndex:s},o=Va.runKernel(Hn,a,i);return{result:o[0],indexes:o[1]}}}),op=ai({mean_:function(e,t=null,n=!1){const r={x:ti(e,"x","mean")},s={axis:t,keepDims:n};return Va.runKernel(qn,r,s)}});function up(e,t="float32"){if(Ue(e),"complex64"===t){const t=up(e,"float32"),n=up(e,"float32");return ii(t,n)}const n=Be(le(e),t);return Va.makeTensor(n,e,t)}function lp(e,t="float32"){if(Ue(e),"complex64"===t){const t=lp(e,"float32"),n=up(e,"float32");return ii(t,n)}const n=Pe(le(e),t);return Va.makeTensor(n,e,t)}function cp(e,t,{indexing:n="xy"}={}){if("xy"!==n&&"ij"!==n)throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(void 0===e)return[];let r=ti(e,"x","meshgrid",e instanceof wa?e.dtype:"float32");if(void 0===t)return[r];let s=ti(t,"y","meshgrid",t instanceof wa?t.dtype:"float32");const a=le(r.shape),i=le(s.shape);return"xy"===n?(r=vc(r,[1,-1]),s=vc(s,[-1,1]),[Hu(lp([i,1],r.dtype),r),Hu(s,lp([1,a],s.dtype))]):(r=vc(r,[-1,1]),s=vc(s,[1,-1]),[Hu(r,lp([1,i],r.dtype)),Hu(lp([a,1],s.dtype),s)])}const hp=ai({minimum_:function(e,t){let n=ti(e,"a","minimum"),r=ti(t,"b","minimum");[n,r]=Fa(n,r),"bool"===n.dtype&&(n=Lo(n,"int32"),r=Lo(r,"int32")),bu(n.shape,r.shape);const s={a:n,b:r};return Va.runKernel(Xn,s)}}),pp=ai({mirrorPad_:function(e,t,n){ie("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const r=ti(e,"x","mirrorPad");if(0===r.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");ie(t.length===r.rank,(()=>`Padding doesn't match input. Must be ${r.rank}. Got ${t.length}.`));const s="reflect"===n?1:0;for(let e=0;e<r.rank;e++)ie(2===t[e].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),ie(t[e][0]>=0&&t[e][0]<=r.shape[e]-s&&t[e][1]>=0&&t[e][1]<=r.shape[e]-s,(()=>`Padding in dimension ${e} cannot be greater than or equal to ${r.shape[e]-s} or less than 0 for input of shape ${r.shape}`));const a={paddings:t,mode:n},i={x:r};return Va.runKernel(Yn,i,a)}}),dp=ai({mod_:function(e,t){let n=ti(e,"a","mod"),r=ti(t,"b","mod");[n,r]=Fa(n,r);const s={a:n,b:r};return Va.runKernel(Jn,s)}}),fp=ai({moments_:function(e,t=null,n=!1){const r=we(t,(e=ti(e,"x","moments")).shape),s=op(e,r,n);let a=s.shape;n||(a=yh(s.shape,r));const i=Ho(du(Lo(e,"float32"),vc(s,a)));return{mean:s,variance:op(i,r,n)}}}),mp=ai({multiRNNCell_:function(e,t,n,r){const s=ti(t,"data","multiRNNCell"),a=ni(n,"c","multiRNNCell"),i=ni(r,"h","multiRNNCell");let o=s;const u=[];for(let t=0;t<e.length;t++){const n=e[t](o,a[t],i[t]);u.push(n[0]),u.push(n[1]),o=n[1]}const l=[],c=[];for(let e=0;e<u.length;e+=2)l.push(u[e]),c.push(u[e+1]);return[l,c]}}),gp=ai({multinomial_:function(e,t,n,r=!1){const s=ti(e,"logits","multinomial"),a=s.size,i=s.rank;if(a<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${a}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);n=n||Math.random();const o={logits:1===i?vc(s,[1,-1]):s},u={numSamples:t,seed:n,normalized:r},l=Va.runKernel(Zn,o,u);return 1===i?vc(l,[l.size]):l}}),yp=ai({notEqual_:function(e,t){let n=ti(e,"a","notEqual","string_or_numeric"),r=ti(t,"b","notEqual","string_or_numeric");[n,r]=Fa(n,r),bu(n.shape,r.shape);const s={a:n,b:r};return Va.runKernel(tr,s)}}),bp=ai({onesLike_:function(e){const t={x:ti(e,"x","onesLike")};return Va.runKernel(ar,t)}}),xp=ai({outerProduct_:function(e,t){const n=ti(e,"v1","outerProduct"),r=ti(t,"v2","outerProduct");ie(1===n.rank&&1===r.rank,(()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`));const s=vc(n,[-1,1]),a=vc(r,[1,-1]);return Hu(s,a)}}),wp=ai({pad_:function(e,t,n=0){const r=ti(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const s={paddings:t,constantValue:n},a={x:r};return Va.runKernel(ur,a,s)}}),vp=ai({pad1d_:function(e,t,n=0){return ie(2===t.length,(()=>"Invalid number of paddings. Must be length of 2.")),wp(e,[t],n)}}),kp=ai({pad2d_:function(e,t,n=0){return ie(2===t.length&&2===t[0].length&&2===t[1].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),wp(e,t,n)}}),Ip=ai({pad3d_:function(e,t,n=0){return ie(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),wp(e,t,n)}}),Np=ai({pad4d_:function(e,t,n=0){return ie(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),wp(e,t,n)}}),Sp=ai({spaceToBatchND_:function(e,t,n){const r=ti(e,"x","spaceToBatchND");ie(r.rank>=1+t.length,(()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`)),ie(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),ie(r.shape.reduce(((e,r,s)=>s>0&&s<=t.length?e&&(r+n[s-1][0]+n[s-1][1])%t[s-1]==0:e),!0),(()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`));const s={x:r},a={blockShape:t,paddings:n};return Va.runKernel(Ur,s,a)}}),Tp=ai({pool_:function(e,t,n,r,s,a,i){null==s&&(s=[1,1]),null==a&&(a=1),0===r&&(r="valid");const o=ti(e,"x","maxPool");let u=o,l=!1;3===o.rank&&(l=!0,u=vc(o,[1,o.shape[0],o.shape[1],o.shape[2]])),ie(yc(a,s),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`));const c=oc(u.shape,t,a,s,r),h=[c.dilationHeight,c.dilationWidth];let p;p="same"===r?function(e,t){const n=e.map(((e,n)=>e+(e-1)*(t[n]-1))).map((e=>e-1)),r=n.map((e=>Math.floor(e/2))),s=n.map(((e,t)=>e-r[t]));return n.map(((e,t)=>[r[t],s[t]]))}([c.filterHeight,c.filterWidth],h):[[0,0],[0,0]];const d=1===h[0]&&1===h[1],[f,m]=function(e,t,n){const r=n.map((e=>e[0])),s=n.map((e=>e[1])),a=e.concat(r,s),i=t.map(((e,t)=>(e-a[t]%e)%e)),o=s.map(((e,t)=>e+i[t]));return[t.map(((e,t)=>[r[t],o[t]])),t.map(((e,t)=>[0,i[t]]))]}([c.inHeight,c.inWidth],h,p),g=d?r:"valid",y=d?u:Sp(u,h,f),b=("avg"===n?()=>kc(y,t,a,g,i):()=>sp(y,t,a,g,i))(),x=d?b:Ec(b,h,m);return l?vc(x,[x.shape[1],x.shape[2],x.shape[3]]):x}}),Cp=ai({prelu_:function(e,t){const n={x:ti(e,"x","prelu"),alpha:ti(t,"alpha","prelu")};return Va.runKernel(hr,n)}}),$p=ai({prod_:function(e,t=null,n=!1){let r=ti(e,"x","prod");"bool"===r.dtype&&(r=Lo(r,"int32"));const s={x:r},a={axis:t,keepDims:n};return Va.runKernel(pr,s,a)}}),Ep=ai({raggedGather_:function(e,t,n,r){const s={paramsNestedSplits:e.map(((e,t)=>ti(e,`tensors${t}`,"raggedGather","int32"))),paramsDenseValues:ti(t,"paramsDenseValues","raggedGather"),indices:ti(n,"indices","raggedGather","int32")},a={outputRaggedRank:r},i=Va.runKernel(dr,s,a);return{outputNestedSplits:i.slice(0,i.length-1),outputDenseValues:i[i.length-1]}}}),Ap=ai({raggedRange_:function(e,t,n){const r=ti(e,"starts","raggedRange"),s={starts:r,limits:ti(t,"limits","raggedRange",r.dtype),deltas:ti(n,"deltas","raggedRange",r.dtype)},a=Va.runKernel(fr,s);return{rtNestedSplits:a[0],rtDenseValues:a[1]}}}),Rp=ai({raggedTensorToTensor_:function(e,t,n,r,s){const a=ti(e,"shape","raggedTensorToTensor","int32"),i=ti(t,"values","raggedTensorToTensor"),o={shape:a,values:i,defaultValue:ti(n,"defaultValue","raggedTensorToTensor",i.dtype),rowPartitionTensors:r.map(((e,t)=>ti(e,`tensors${t}`,"raggedTensorToTensor","int32")))},u={rowPartitionTypes:s};return Va.runKernel(mr,o,u)}}),Op=ai({rand_:function(e,t,n){Ue(e);const r=le(e);let s=null;if(null==n||"float32"===n)s=new Float32Array(r);else if("int32"===n)s=new Int32Array(r);else{if("bool"!==n)throw new Error(`Unknown data type ${n}`);s=new Uint8Array(r)}for(let e=0;e<r;e++)s[e]=t();return Va.makeTensor(s,e,n)}});var Fp=n(7391);class _p{constructor(e,t,n,r,s){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);const a=s||Math.random();this.random=Fp.alea(a.toString())}nextValue(){if(!isNaN(this.nextVal)){const e=this.nextVal;return this.nextVal=NaN,e}let e,t,n=!1;for(;!n;){let r,s,a;do{r=2*this.random()-1,s=2*this.random()-1,a=r*r+s*s}while(a>=1||0===a);const i=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*r*i,t=this.mean+this.stdDev*s*i,this.truncated&&!this.isValidTruncated(e)||(n=!0)}return this.truncated&&!this.isValidTruncated(t)||(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class Dp{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const s=r||Math.random();this.randu=Fp.alea(s.toString()),this.randn=new _p(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,s,a;for(;;){do{r=this.randn.nextValue(),a=1+this.c*r}while(a<=0);if(a*=a*a,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-a+Math.log(a)),s=this.randu(),s<t||Math.log(s)<n)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(a)}convertValue(e){return"float32"===this.dtype?e:Math.round(e)}}class Mp{constructor(e=0,t=1,n,r){if(this.canReturnFloat=()=>null==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=Fp.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const Lp=ai({randomGamma_:function(e,t,n=1,r="float32",s){if(Ue(e),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const a=new Dp(t,n,r,s),i=Mo(e,r);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}}),zp=ai({randomNormal_:function(e,t=0,n=1,r,s){if(Ue(e),null!=r&&"bool"===r)throw new Error(`Unsupported data type ${r}`);const a=new _p(t,n,r,!1,s),i=Mo(e,r);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}}),Pp=ai({randomStandardNormal_:function(e,t,n){if(null!=t&&"bool"===t)throw new Error(`Unsupported data type ${t}`);return zp(e,0,1,t,n)}}),Bp=ai({randomUniform_:function(e,t=0,n=1,r="float32",s){Ue(e);const a=Mo(e,r),i=new Mp(t,n,null,s);for(let e=0;e<a.values.length;e++)a.values[e]=i.nextValue();return a.toTensor()}}),Wp=ai({randomUniformInt_:function(e,t,n,r){return Bp(e,t,n,"int32",r)}});function Up(e,t,n=1,r="float32"){if(0===n)throw new Error("Cannot have a step of zero");const s={start:e,stop:t,step:n,dtype:r};return Va.runKernel(gr,{},s)}const Vp=ai({reciprocal_:function(e){const t={x:ti(e,"x","reciprocal")};return Va.runKernel(br,t)}}),Gp=ai({relu_:function(e){const t={x:ti(e,"x","relu")};return Va.runKernel(xr,t)}}),jp=ai({relu6_:function(e){const t={x:ti(e,"x","relu6")};return Va.runKernel(Sr,t)}}),Hp=ai({reverse_:function(e,t){const n={x:ti(e,"x","reverse")},r={dims:t};return Va.runKernel(Tr,n,r)}}),qp=ai({reverse1d_:function(e){const t=ti(e,"x","reverse");return ie(1===t.rank,(()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),Hp(t,0)}}),Kp=ai({reverse2d_:function(e,t){const n=ti(e,"x","reverse");return ie(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),Hp(n,t)}}),Xp=ai({reverse3d_:function(e,t){const n=ti(e,"x","reverse");return ie(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),Hp(n,t)}}),Yp=ai({reverse4d_:function(e,t){const n=ti(e,"x","reverse");return ie(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),Hp(n,t)}}),Jp=ai({round_:function(e){const t={x:ti(e,"x","round")};return Va.runKernel(Cr,t)}}),Zp=ai({rsqrt_:function(e){const t={x:ti(e,"x","rsqrt","float32")};return Va.runKernel($r,t)}}),Qp=ai({selu_:function(e){const t={x:ti(e,"x","selu")};return Va.runKernel(Fr,t)}}),ed=ai({separableConv2d_:function(e,t,n,r,s,a=[1,1],i="NHWC"){const o=ti(e,"x","separableConv2d"),u=ti(t,"depthwiseFilter","separableConv2d"),l=ti(n,"pointwiseFilter","separableConv2d");let c=o,h=!1;if(3===o.rank&&(h=!0,c=vc(o,[1,o.shape[0],o.shape[1],o.shape[2]])),"NCHW"===i)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");ie(4===c.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`)),ie(4===u.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${u.rank}.`)),ie(4===l.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${u.rank}.`)),ie(1===l.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${l.shape[0]}.`)),ie(1===l.shape[1],(()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${l.shape[1]}.`));const p=u.shape[2],d=u.shape[3];ie(l.shape[2]===p*d,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*d}, but got ${l.shape[2]}.`));const f=rh(c,u,r,s,i,a),m=Gc(f,l,1,"valid",i);return h?vc(m,[m.shape[1],m.shape[2],m.shape[3]]):m}}),td=async function(e,t){const n=ti(e,"x","setdiff1d"),r=ti(t,"y","setdiff1d");ie(n.dtype===r.dtype,(()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`)),ie(1===n.rank,(()=>`x should be 1D tensor, but got x (${n.shape}).`)),ie(1===r.rank,(()=>`y should be 1D tensor, but got y (${r.shape}).`));const s=await n.data(),a=await r.data(),i=new Set(a);let o=0;for(let e=0;e<s.length;e++)i.has(s[e])||o++;const u=new ga([o],n.dtype),l=new ga([o],"int32");for(let e=0,t=0;e<s.length;e++)i.has(s[e])||(u.values[t]=s[e],l.values[t]=e,t++);return[u.toTensor(),l.toTensor()]},nd=ai({sign_:function(e){const t={x:ti(e,"x","sign")};return Va.runKernel(Lr,t)}}),rd=ai({sin_:function(e){const t={x:ti(e,"x","sin","float32")};return Va.runKernel(Dr,t)}}),sd=ai({sinh_:function(e){const t={x:ti(e,"x","sinh")};return Va.runKernel(Mr,t)}}),ad=ai({slice1d_:function(e,t,n){const r=ti(e,"x","slice1d");return ie(1===r.rank,(()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`)),Tc(r,[t],[n])}}),id=ai({slice2d_:function(e,t,n){const r=ti(e,"x","slice2d");return ie(2===r.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`)),Tc(r,t,n)}}),od=ai({slice3d_:function(e,t,n){const r=ti(e,"x","slice3d");return ie(3===r.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`)),Tc(r,t,n)}}),ud=ai({slice4d_:function(e,t,n){const r=ti(e,"x","slice4d");return ie(4===r.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`)),Tc(r,t,n)}}),ld=ai({softmax_:function(e,t=-1){const n=ti(e,"logits","softmax","float32");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const r={logits:n},s={dim:t};return Va.runKernel(Gr,r,s)}}),cd=ai({fft_:function(e){ie("complex64"===e.dtype,(()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`));const t={input:e};return Va.runKernel(ln,t)}}),hd=ai({ifft_:function(e){ie("complex64"===e.dtype,(()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`));const t={input:e};return Va.runKernel(wn,t)}}),pd=ai({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const s=vc(e,[n,t]);r=hd(s)}else{const s=[n,2*(t-1)],a=vc(Yu(e),[n,t]),i=vc(Ku(e),[n,t]),o=Hp(Tc(a,[0,1],[n,t-2]),1),u=Go(Hp(Tc(i,[0,1],[n,t-2]),1),tu(-1)),l=Nc([a,o],1),c=Nc([i,u],1),h=vc(ii(l,c),[s[0],s[1]]);r=hd(h)}if(r=Yu(r),3===e.rank&&0!==e.shape[0]){const t=r,n=e.shape[0];r=vc(r,[n,r.shape[0]/n,r.shape[1]]),t.dispose()}return r}}),dd=ai({split_:function(e,t,n=0){const r={x:ti(e,"x","split")},s={numOrSizeSplits:t,axis:n};return Va.runKernel(Vr,r,s)}}),fd=ai({rfft_:function(e,t){ie("float32"===e.dtype,(()=>`The dtype for rfft() must be real value but got ${e.dtype}`));let n=e.shape[e.shape.length-1];const r=e.size/n;let s;if(null!=t&&t<n){const r=e.shape.map((e=>0)),a=e.shape.map((e=>e));a[e.shape.length-1]=t,s=Tc(e,r,a),n=t}else if(null!=t&&t>n){const r=e.shape.map((e=>e));r[e.shape.length-1]=t-n,s=Nc([e,up(r)],e.shape.length-1),n=t}else s=e;const a=qo(s),i=vc(ii(s,a),[r,n]),o=cd(i),u=Math.floor(n/2)+1,l=Yu(o),c=Ku(o),h=dd(l,[u,n-u],l.shape.length-1),p=dd(c,[u,n-u],c.shape.length-1),d=s.shape.slice();return d[s.shape.length-1]=u,vc(ii(h[0],p[0]),d)}}),md=ai({squaredDifference_:function(e,t){let n=ti(e,"a","squaredDifference"),r=ti(t,"b","squaredDifference");[n,r]=Fa(n,r),bu(n.shape,r.shape);const s={a:n,b:r};return Va.runKernel(Yr,s,{})}}),gd=ai({squeeze_:function(e,t){const n=ti(e,"x","squeeze","string_or_numeric");return vc(n,ve(n.shape,t).newShape)}}),yd=ai({stack_:function(e,t=0){const n=ni(e,"tensors","stack","string_or_numeric");ie(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&ie(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const r=n,s={axis:t};return Va.runKernel(or,r,s)}}),bd=ai({step_:function(e,t=0){const n={x:ti(e,"x","step")},r={alpha:t};return Va.runKernel(ms,n,r)}}),xd=ai({stridedSlice_:function(e,t,n,r,s=0,a=0,i=0,o=0,u=0){const l={x:ti(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:r,beginMask:s,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:u};return Va.runKernel(Qr,l,c)}}),wd=ai({tan_:function(e){const t={x:ti(e,"x","tan","float32")};return Va.runKernel(ss,t)}});function vd(e,t){ue(e);const n=Za(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return oi(e,null,n,t)}function kd(e,t,n){if(ue(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const r=Za(e,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return oi(e,t,r,n)}function Id(e,t,n){if(ue(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const r=Za(e,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return oi(e,t,r,n)}function Nd(e,t,n){if(ue(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const r=Za(e,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return oi(e,t,r,n)}function Sd(e,t,n){if(ue(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const r=Za(e,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return oi(e,t=t||r,r,n)}const Td=ai({tensorScatterUpdate_:function(e,t,n){const r=ti(e,"tensor","tensorScatterupdate"),s=ti(t,"indices","tensorScatterupdate","int32"),a=ti(n,"updates","tensorScatterupdate");if(hl(a,s,r.shape),r.dtype!==a.dtype)throw new Error(`tensor and updates must have the same dtype, instead they are ${r.dtype} and ${a.dtype}.`);const i={tensor:r,indices:s,updates:a};return Va.runKernel(Ar,i,{})}}),Cd=ai({topk_:function(e,t=1,n=!0){const r=ti(e,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");const s=r.shape[r.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>s)throw new Error(`'k' passed to topk() must be <= the last dimension (${s}) but got ${t}`);const a={x:r},i={k:t,sorted:n},[o,u]=Va.runKernel(os,a,i);return{values:o,indices:u}}}),$d=ai({truncatedNormal_:function(e,t=0,n=1,r,s){if(Ue(e),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const a=new _p(t,n,r,!0,s),i=Mo(e,r);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}}),Ed=ai({unique_:function(e,t=0){const n=ti(e,"x","unique","string_or_numeric");ie(n.rank>0,(()=>"The input tensor must be at least 1D"));const r={x:n},s={axis:t},[a,i]=Va.runKernel(cs,r,s);return{values:a,indices:i}}}),Ad=ai({unsortedSegmentSum_:function(e,t,n){const r=ti(e,"x","unsortedSegmentSum"),s=ti(t,"segmentIds","unsortedSegmentSum","int32");ie(de(n),(()=>"numSegments must be of dtype int"));const a={x:r,segmentIds:s},i={numSegments:n};return Va.runKernel(ps,a,i)}}),Rd=ai({unstack_:function(e,t=0){const n=ti(e,"x","unstack","string_or_numeric");ie(t>=-n.shape.length&&t<n.shape.length,(()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const r={value:n},s={axis:t};return Va.runKernel(hs,r,s)}});function Od(e,t){return np(e,t,"right")}function Fd(e,t=!0,n,r){return Va.makeVariable(e,t,n,r)}function _d(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const r=Mo(e,"int32"),s=Mo([n.length,e.length],"int32");for(let t=0;t<n.length;t++){const a=r.indexToLoc(n[t]),i=t*e.length;s.values.set(a,i)}return s.toTensor()}const Dd=async function(e){const t=ti(e,"condition","whereAsync","bool"),n=await t.data(),r=_d(t.shape,n);return e!==t&&t.dispose(),r},Md=async function(e,t,n){const r=ti(e,"tensor","boolMask"),s=ti(t,"mask","boolMask","bool"),a=null==n?0:n,i=s.rank,o=r.shape;ie(i>0,(()=>"mask cannot be scalar")),oe(o.slice(a,a+i),s.shape,"mask's shape must match the first K dimensions of tensor's shape,");let u=1;for(let e=a;e<a+i;e++)u*=o[e];const l=o.slice(0,a).concat([u],o.slice(a+i)),c=vc(r,l),h=vc(s,[-1]),p=await Dd(h),d=gd(p,[1]),f=_h(c,d,a);return e!==r&&r.dispose(),t!==s&&s.dispose(),d.dispose(),c.dispose(),h.dispose(),p.dispose(),f},Ld=ai({movingAverage_:function(e,t,n,r,s=!0){const a=ti(e,"v","movingAverage"),i=ti(t,"x","movingAverage"),o=ti(n,"decay","movingAverage");_a(a,i),ie(pe(a.shape,i.shape),(()=>"Shape mismatch in v and x"));const u=tu(1),l=du(u,o);let c=Go(du(i,a),l);if(s){ie(null!=r,(()=>"When using zeroDebias: true, step is required."));const e=ti(r,"step","movingAverage");c=Vo(c,du(u,pu(o,e)))}return Wo(a,c)}}),zd=ai({scatterND_:function(e,t,n){Ue(n);const r=ti(e,"indices","scatterND","int32"),s=ti(t,"updates","scatterND");hl(s,r,n);const a={indices:r,updates:s},i={shape:n};return Va.runKernel(Er,a,i)}}),Pd=ai({sparseToDense_:function(e,t,n,r=0){Ue(n);const s=ti(e,"sparseIndices","sparseToDense","int32"),a=ti(t,"sparseValues","sparseToDense","string_or_numeric"),i=ti(r,"defaultValue","sparseToDense",a.dtype);!function(e,t,n,r){if("int32"!==e.dtype)throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const s=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(n.length!==a)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${a}.`);const i=t.size;if(0!==t.rank&&(1!==t.rank||i!==s))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${s}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(s,a,n,i);const o={sparseIndices:s,sparseValues:a,defaultValue:i},u={outputShape:n};return Va.runKernel(Xr,o,u)}}),Bd=ai({gatherND_:function(e,t){const n=ti(t,"indices","gatherND","int32"),r={params:ti(e,"x","gatherND","string_or_numeric"),indices:n};return Va.runKernel(gn,r)}}),Wd=ai({dropout_:function(e,t,n,r){const s=ti(e,"x","dropout");if(ie("float32"===s.dtype,(()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${s.dtype} tensor instead.`)),ie(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof wa?s.clone():s;const a=function(e,t){if(null==t)return e.shape.slice();if(pe(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let r=0;r<e.shape.length;r++)null==t[r]&&null!=e.shape[r]?n.push(e.shape[r]):n.push(t[r]);return n}return t}(s,n),i=1-t,o=Vo(Fh(Wo(Bp(a,0,1,"float32",r),i)),i);return Go(s,o)}});function Ud(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function Vd(e,t,n){const r=1-e%2,s=new Float32Array(e);for(let a=0;a<e;++a){const i=2*Math.PI*a/(e+r-1);s[a]=t-n*Math.cos(i)}return vd(s,"float32")}const Gd=async function(e,t,n=1){const r=ti(e,"predictions","inTopK"),s=ti(t,"targets","inTopK");ie(r.rank>1,(()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`)),ie(r.rank-1===s.rank,(()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${s.rank}`)),oe(r.shape.slice(0,r.shape.length-1),s.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const a=r.shape[r.shape.length-1];ie(n>0&&n<=a,(()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`));const i=await r.data(),o=await s.data(),[u,l]=[i.length/a,a],c=ke("bool",u);for(let e=0;e<u;e++){const t=e*l,r=i.subarray(t,t+l),s=[];for(let e=0;e<r.length;e++)s.push({value:r[e],index:e});s.sort(((e,t)=>t.value-e.value)),c[e]=0;for(let t=0;t<n;t++)if(s[t].index===o[e]){c[e]=1;break}}return e!==r&&r.dispose(),t!==s&&s.dispose(),ui(c,s.shape,"bool")},jd=ai({conv2DBackpropFilter_:function(e,t,n,r,s,a="NHWC",i){let o=e;3===e.rank&&(o=vc(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=vc(t,[1,t.shape[0],t.shape[1],t.shape[2]])),ie(4===o.rank,(()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`)),ie(4===u.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${u.shape}.`)),ie(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const l="NHWC"===a?o.shape[3]:o.shape[1],c="NHWC"===a?u.shape[3]:u.shape[1];ie(l===n[2],(()=>`Error in conv2dDerFilter: depth of input ${l}) must match input depth in filter (${n[2]}.`)),ie(c===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${n[3]}).`)),wc("conv2dDerFilter",s,i);const h={x:o,dy:u},p={strides:r,pad:s,dataFormat:a,dimRoundingMode:i,filterShape:n};return Va.runKernel(Ft,h,p)}});function Hd(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Go(e,bd(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function qd(e,t){let n=t;const r=yu(e.shape,t.shape);return r.length>0&&(n=Nh(n,r)),vc(n,e.shape)}function Kd(e,t,n,r){if("linear"===t)return e;if("relu"===t)return Gp(e);if("elu"===t)return hh(e);if("relu6"===t)return jp(e);if("prelu"===t)return Cp(e,n);if("leakyrelu"===t)return Bh(e,r);if("sigmoid"===t)return Sc(e);throw new Error(`Unknown fused activation ${t}.`)}const Xd=(e,t)=>!(e>0)||"linear"===t,Yd=ai({fusedConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:u="linear",preluActivationWeights:l,leakyreluAlpha:c}){if(u=u||"linear",!1===Xd(Va.state.gradientDepth,u)){ie("NHWC"===s,(()=>`Error in fused conv2d: got dataFormat of ${s} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`));let h=Gc(e,t,n,r,s,a,i);return null!=o&&(h=Wo(h,o)),Kd(h,u,l,c)}const h=ti(e,"x","conv2d","float32"),p=ti(t,"filter","conv2d","float32");let d=h,f=!1;3===h.rank&&(f=!0,d=vc(h,[1,h.shape[0],h.shape[1],h.shape[2]])),ie(4===d.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`)),ie(4===p.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`)),wc("fused conv2d",r,i);const m="NHWC"===s?d.shape[3]:d.shape[1];ie(p.shape[2]===m,(()=>`Error in conv2d: depth of input (${m}) must match input depth for filter ${p.shape[2]}.`)),ie(yc(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`));const g=lc(d.shape,p.shape,n,a,r,i);let y,b;if(null!=o&&(y=ti(o,"bias","fused conv2d"),[y]=Fa(y,h),"NHWC"===s?bu(g.outShape,y.shape):(ie(y.shape.length<=1,(()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${y.shape.length}.`)),ie(0===y.shape.length||y.shape[0]===g.outChannels||1===y.shape[0],(()=>`Error in fused conv2d: bias shape (${y.shape}) is not compatible with the number of output channels (${g.outChannels})`)))),null!=l){const e=l.shape;if(ie(e.length<=1||3===e.length,(()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${e.length}.`)),1===e.length)ie(1===e[0]||e[0]===g.outChannels,(()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${g.outChannels}).`));else if(3===e.length)try{bu(e,g.outShape)}catch(t){const n=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(n)}b=ti(l,"prelu weights","fused conv2d")}const x=(e,t)=>{ie("NHWC"===s,(()=>`Error in gradient of fused conv2D: got dataFormat of ${s} but only NHWC is currently supported.`));const[i,o,l,c]=t,h=Hd(e,l,u);ie(gc(a),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`));const p=[Hc(o.shape,h,i,n,r),jd(o,h,i.shape,n,r)];if(null!=c){const e=qd(c,h);p.push(e)}return p},w={x:d,filter:p,bias:y,preluActivationWeights:b},v={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i,activation:u,leakyreluAlpha:c};if(null==o){const e=Qo(((e,t,n)=>{let r=Va.runKernel(xs,w,v);return n([t,e,r]),f&&(r=vc(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:x}}));return e(d,p)}{const e=Qo(((e,t,n,r)=>{let s=Va.runKernel(xs,w,v);return r([t,e,s,n]),f&&(s=vc(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:x}}));return e(d,p,y)}}}),Jd=ai({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,s,a=[1,1],i){let o=e;3===e.rank&&(o=vc(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=vc(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={x:o,dy:u},c={strides:r,pad:s,dimRoundingMode:i,dilations:a,filterShape:n};return Va.runKernel(Ht,l,c)}}),Zd=ai({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,s,a=[1,1],i){let o=t,u=!1;3===t.rank&&(u=!0,o=vc(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={dy:o,filter:n},c={strides:r,pad:s,dimRoundingMode:i,dilations:a,inputShape:e},h=Va.runKernel(qt,l,c);return u?vc(h,[h.shape[1],h.shape[2],h.shape[3]]):h}}),Qd=ai({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:u="linear",preluActivationWeights:l,leakyreluAlpha:c}){if(!1===Xd(Va.state.gradientDepth,u)){let h=rh(e,t,n,r,s,a,i);return null!=o&&(h=Wo(h,o)),Kd(h,u,l,c)}const h=ti(e,"x","depthwiseConv2d","float32"),p=ti(t,"filter","depthwiseConv2d","float32");let d=h,f=!1;3===h.rank&&(f=!0,d=vc(h,[1,h.shape[0],h.shape[1],h.shape[2]])),ie(4===d.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`)),ie(4===p.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`)),ie(d.shape[3]===p.shape[2],(()=>`Error in fused depthwiseConv2d: number of input channels (${d.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`)),null==a&&(a=[1,1]),ie(yc(n,a),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),wc("fused depthwiseConv2d",r,i);const m=lc(d.shape,p.shape,n,a,r,i,!0);let g,y;null!=o&&(g=ti(o,"bias","fused conv2d"),[g]=Fa(g,h),bu(m.outShape,g.shape)),null!=l&&(y=ti(l,"prelu weights","fused depthwiseConv2d"));const b=(e,t)=>{ie(gc(a),(()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`));const[s,o,l,c]=t,h=Hd(e,l,u),p=Zd(o.shape,h,s,n,r,a,i),d=Jd(o,h,s.shape,n,r,a,i);return null!=c?[p,d,qd(g,h)]:[p,d]},x={x:d,filter:p,bias:g,preluActivationWeights:y},w={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i,activation:u,leakyreluAlpha:c};if(null==o){const e=Qo(((e,t,n)=>{let r=Va.runKernel(ws,x,w);return n([t,e,r]),f&&(r=vc(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:b}}));return e(d,p)}{const e=Qo(((e,t,n,r)=>{let s=Va.runKernel(ws,x,w);return r([t,e,s,n]),f&&(s=vc(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:b}}));return e(d,p,g)}}}),ef=ai({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:s,activation:a="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(!1===Xd(Va.state.gradientDepth,a)){let u=Hu(e,t,n,r);return null!=s&&(u=Wo(u,s)),Kd(u,a,i,o)}let u=ti(e,"a","fused matMul"),l=ti(t,"b","fused matMul");[u,l]=Fa(u,l);const c=n?u.shape[u.rank-2]:u.shape[u.rank-1],h=r?l.shape[l.rank-1]:l.shape[l.rank-2],p=n?u.shape[u.rank-1]:u.shape[u.rank-2],d=r?l.shape[l.rank-2]:l.shape[l.rank-1],f=u.shape.slice(0,-2),m=l.shape.slice(0,-2),g=le(f),y=le(m);ie(c===h,(()=>`Error in fused matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${u.shape} and ${l.shape} and transposeA=${n} and transposeB=${r} must match.`));const b=bu(u.shape.slice(0,-2),l.shape.slice(0,-2)).concat([p,d]),x=vc(u,n?[g,c,p]:[g,p,c]),w=vc(l,r?[y,d,h]:[y,h,d]);let v,k;null!=s&&(v=ti(s,"bias","fused matMul"),[v]=Fa(v,u),bu(b,v.shape)),null!=i&&(k=ti(i,"prelu weights","fused matMul"));const I=(e,t)=>{const[i,o,u,l]=t,c=Hd(vc(e,u.shape),u,a);let h,p;return n||r?!n&&r?(h=Hu(c,o,!1,!1),p=Hu(c,i,!0,!1)):n&&!r?(h=Hu(o,c,!1,!0),p=Hu(i,c,!1,!1)):(h=Hu(o,c,!0,!0),p=Hu(c,i,!0,!0)):(h=Hu(c,o,!1,!0),p=Hu(i,c,!0,!1)),null!=s?[h,p,qd(l,c)]:[h,p]},N={a:x,b:w,bias:v,preluActivationWeights:k},S={transposeA:n,transposeB:r,activation:a,leakyreluAlpha:o};if(null==s){const e=Qo(((e,t,n)=>{const r=Va.runKernel(bs,N,S);return n([e,t,r]),{value:vc(r,b),gradFunc:I}}));return e(x,w)}{const e=Qo(((e,t,n,r)=>{const s=Va.runKernel(bs,N,S);return r([e,t,s,n]),{value:vc(s,b),gradFunc:I}}));return e(x,w,v)}}}),tf=ai({hammingWindow_:function(e){return Vd(e,.54,.46)}}),nf=ai({hannWindow_:function(e){return Vd(e,.5,.5)}}),rf=ai({frame_:function(e,t,n,r=!1,s=0){let a=0;const i=[];for(;a+t<=e.size;)i.push(Tc(e,a,t)),a+=n;if(r)for(;a<e.size;){const r=a+t-e.size,o=Nc([Tc(e,a,t-r),cu([r],s)]);i.push(o),a+=n}return 0===i.length?kd([],[0,t]):vc(Nc(i),[i.length,t])}}),sf=ai({stft_:function(e,t,n,r,s=nf){null==r&&(r=Ud(t));const a=rf(e,t,n),i=Go(a,s(t));return fd(i,r)}}),af=ai({cropAndResize_:function(e,t,n,r,s="bilinear",a=0){const i=ti(e,"image","cropAndResize"),o=ti(t,"boxes","cropAndResize","float32"),u=ti(n,"boxInd","cropAndResize","int32"),l=o.shape[0];ie(4===i.rank,(()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`)),ie(2===o.rank&&4===o.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${l},4] but had shape ${o.shape}.`)),ie(1===u.rank&&u.shape[0]===l,(()=>`Error in cropAndResize: boxInd must be have size [${l}] but had shape ${o.shape}.`)),ie(2===r.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`)),ie(r[0]>=1&&r[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${r}`)),ie("bilinear"===s||"nearest"===s,(()=>`method must be bilinear or nearest, but was ${s}`));const c={image:i,boxes:o,boxInd:u},h={method:s,extrapolationValue:a,cropSize:r};return Va.runKernel(Ut,c,h)}}),of=ai({flipLeftRight_:function(e){const t=ti(e,"image","flipLeftRight","float32");ie(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return Va.runKernel(hn,n,{})}}),uf=ai({grayscaleToRGB_:function(e){const t=ti(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];ie(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),ie(1===r,(()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${r}.`));const s=new Array(t.rank);return s.fill(1,0,n),s[n]=3,Rh(t,s)}}),lf=ai({rgbToGrayscale_:function(e){const t=ti(e,"image","RGBToGrayscale"),n=t.rank-1,r=t.shape[n];ie(t.rank>=2,(()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`)),ie(3===r,(()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${r}.`));const s=t.dtype,a=Lo(t,"float32"),i=vd([.2989,.587,.114]);let o;switch(t.rank){case 2:o=ch("ij,j->i",a,i);break;case 3:o=ch("ijk,k->ij",a,i);break;case 4:o=ch("ijkl,l->ijk",a,i);break;case 5:o=ch("ijklm,m->ijkl",a,i);break;case 6:o=ch("ijklmn,n->ijklm",a,i);break;default:throw new Error("Not a valid tensor rank.")}return o=Eh(o,-1),Lo(o,s)}}),cf=ai({rotateWithOffset_:function(e,t,n=0,r=.5){const s=ti(e,"image","rotateWithOffset","float32");ie(4===s.rank,(()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${s.rank}.`));const a={image:s},i={radians:t,fillValue:n,center:r};return Va.runKernel(ys,a,i)}});function hf(e,t,n,r,s,a){null==r&&(r=.5),null==s&&(s=Number.NEGATIVE_INFINITY),null==a&&(a=0);const i=e.shape[0];return n=Math.min(n,i),ie(0<=r&&r<=1,(()=>`iouThreshold must be in [0, 1], but was '${r}'`)),ie(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),ie(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),ie(1===t.rank,(()=>"scores must be a 1D tensor")),ie(t.shape[0]===i,(()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`)),ie(0<=a&&a<=1,(()=>`softNmsSigma must be in [0, 1], but was '${a}'`)),{maxOutputSize:n,iouThreshold:r,scoreThreshold:s,softNmsSigma:a}}const pf=ai({nonMaxSuppression_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){const a=ti(e,"boxes","nonMaxSuppression","float32"),i=ti(t,"scores","nonMaxSuppression","float32"),o=hf(a,i,n,r,s),u={maxOutputSize:n=o.maxOutputSize,iouThreshold:r=o.iouThreshold,scoreThreshold:s=o.scoreThreshold};return Va.runKernel(nr,{boxes:a,scores:i},u)}});function df(e,t,n){const r=function(e,t,n){return function(e,t,n){let r=0,s=e.length,a=0,i=!1;for(;r<s;){a=r+(s-r>>>1);const o=n(t,e[a]);o>0?r=a+1:(s=a,i=!o)}return i?r:-r-1}(e,t,n||ff)}(e,t,n),s=r<0?-(r+1):r;e.splice(s,0,t)}function ff(e,t){return e>t?1:e<t?-1:0}function mf(e,t,n,r,s){return bf(e,t,n,r,s,0)}function gf(e,t,n,r,s,a){return bf(e,t,n,r,s,0,!1,a,!0)}function yf(e,t,n,r,s,a){return bf(e,t,n,r,s,a,!0)}function bf(e,t,n,r,s,a,i=!1,o=!1,u=!1){const l=[];for(let e=0;e<t.length;e++)t[e]>s&&l.push({score:t[e],boxIndex:e,suppressBeginIndex:0});l.sort(vf);const c=a>0?-.5/a:0,h=[],p=[];for(;h.length<n&&l.length>0;){const t=l.pop(),{score:n,boxIndex:a,suppressBeginIndex:i}=t;if(n<s)break;let o=!1;for(let n=h.length-1;n>=i;--n){const i=xf(e,a,h[n]);if(i>=r){o=!0;break}if(t.score=t.score*wf(r,c,i),t.score<=s)break}t.suppressBeginIndex=h.length,o||(t.score===n?(h.push(a),p.push(t.score)):t.score>s&&df(l,t,vf))}const d=h.length,f=n-d;o&&f>0&&(h.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));const m={selectedIndices:h};return i&&(m.selectedScores=p),u&&(m.validOutputs=d),m}function xf(e,t,n){const r=e.subarray(4*t,4*t+4),s=e.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),i=Math.min(r[1],r[3]),o=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(s[0],s[2]),c=Math.min(s[1],s[3]),h=Math.max(s[0],s[2]),p=Math.max(s[1],s[3]),d=(o-a)*(u-i),f=(h-l)*(p-c);if(d<=0||f<=0)return 0;const m=Math.max(a,l),g=Math.max(i,c),y=Math.min(o,h),b=Math.min(u,p),x=Math.max(y-m,0)*Math.max(b-g,0);return x/(d+f-x)}function wf(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function vf(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const kf=ai({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=0){const i=ti(e,"boxes","nonMaxSuppression"),o=ti(t,"scores","nonMaxSuppression"),u=hf(i,o,n,r,s,a),l={boxes:i,scores:o},c={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:s=u.scoreThreshold,softNmsSigma:a=u.softNmsSigma},h=Va.runKernel(sr,l,c);return{selectedIndices:h[0],selectedScores:h[1]}}}),If=ai({nonMaxSuppressionPadded_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){const i=ti(e,"boxes","nonMaxSuppression"),o=ti(t,"scores","nonMaxSuppression"),u=hf(i,o,n,r,s,null),l={boxes:i,scores:o},c={maxOutputSize:u.maxOutputSize,iouThreshold:u.iouThreshold,scoreThreshold:u.scoreThreshold,padToMaxOutputSize:a},h=Va.runKernel(rr,l,c);return{selectedIndices:h[0],validOutputs:h[1]}}}),Nf=ai({resizeBilinear_:function(e,t,n=!1,r=!1){const s=ti(e,"images","resizeBilinear");ie(3===s.rank||4===s.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}.`)),ie(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),ie(!1===r||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let a=s,i=!1;3===s.rank&&(i=!0,a=vc(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const[]=t,o={images:a},u={alignCorners:n,halfPixelCenters:r,size:t},l=Va.runKernel(Ir,o,u);return i?vc(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}),Sf=ai({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const s=ti(e,"images","resizeNearestNeighbor");ie(3===s.rank||4===s.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${s.rank}.`)),ie(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),ie("float32"===s.dtype||"int32"===s.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),ie(!1===r||!1===n,(()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false."));let a=s,i=!1;3===s.rank&&(i=!0,a=vc(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const[]=t,o={images:a},u={alignCorners:n,halfPixelCenters:r,size:t},l=Va.runKernel(vr,o,u);return i?vc(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}),Tf=ai({threshold_:function(e,t="binary",n=!1,r=.5){const s=ti(e,"image","threshold"),a=s.shape[0]*s.shape[1];let i,o,u,l,c=Go(vd([r]),255);if(ie(3===s.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${s.rank}.`)),ie(3===s.shape[2]||1===s.shape[2],(()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${s.shape[2]}.`)),ie("int32"===s.dtype||"float32"===s.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${s.dtype}.`)),ie("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===s.shape[2]){[i,o,u]=dd(s,[1,1,1],-1);const e=Go(i,.2989),t=Go(o,.587),n=Go(u,.114);l=Wo(Wo(e,t),n)}else l=e;"otsu"===t&&(c=function(e,t){let n,r,s,a,i,o,u=vd([-1]),l=vd([0]),c=vd([0]);for(let h=0;h<e.size-1;h++){n=Tc(e,0,h+1),r=Tc(e,h+1),i=Vo(Nh(n),t),o=Vo(Nh(r),t);const p=Nh(Go(n,Up(0,n.size)));s=Vo(p,Nh(n));const d=cu(r.shape,n.size),f=Wo(Up(0,r.size),d),m=Go(r,f);a=Vo(Nh(m),Nh(r));const g=du(s,a),y=du(s,a),b=Go(i,o);c=Go(Go(b,g),y);const x=Dh(c,l);l=oh(x,c,l),u=oh(x,vd([h]),u)}return u}(_c(Lo(Jp(l),"int32"),ui([]),256),a));const h=n?Uh(l,c):Dh(l,c);return Lo(Go(h,255),"int32")}}),Cf=ai({transform_:function(e,t,n="nearest",r="constant",s=0,a){const i=ti(e,"image","transform","float32"),o=ti(t,"transforms","transform","float32");ie(4===i.rank,(()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`)),ie(2===o.rank&&(o.shape[0]===i.shape[0]||1===o.shape[0])&&8===o.shape[1],(()=>"Error in transform: Input transform should be batch x 8 or 1 x 8")),ie(null==a||2===a.length,(()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`));const u={image:i,transforms:o},l={interpolation:n,fillMode:r,fillValue:s,outputShape:a};return Va.runKernel(us,u,l)}}),$f=ai({bandPart_:function(e,t,n){const r=ti(e,"a","bandPart");ie(r.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`));const s=r.shape,[a,i]=r.shape.slice(-2);let o,u;"number"==typeof t?(ie(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),ie(t<=a,(()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`)),o=ti(t<0?a:t,"numLower","bandPart")):(ie("int32"===t.dtype,(()=>"bandPart(): numLower's dtype must be an int32.")),o=oh(Wh(t,0),a,hp(t,a))),"number"==typeof n?(ie(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`)),ie(n<=i,(()=>`bandPart(): numUpper (${n}) must not be greater than the number of columns (${i}).`)),u=ti(n<0?i:n,"numUpper","bandPart")):(ie("int32"===n.dtype,(()=>"bandPart(): numUpper's dtype must be an int32.")),u=oh(Wh(n,0),i,hp(n,i)));const l=vc(Up(0,a,1,"int32"),[-1,1]),c=Up(0,i,1,"int32"),h=du(l,c),p=Jh(Uh(h,o),Mh(h,Xu(u))),d=up([a,i],r.dtype);return vc(yd(Rd(vc(r,[-1,a,i])).map((e=>oh(p,e,d)))),s)}}),Ef=ai({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,ie(null!=e&&e.length>0,(()=>"Gram-Schmidt process: input must not be null, undefined, or empty"));const n=e[0].shape[0];for(let t=1;t<e.length;++t)ie(e[t].shape[0]===n,(()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`))}else t=!0,e=dd(e,e.shape[0],0).map((e=>gd(e,[0])));ie(e.length<=e[0].shape[0],(()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`));const n=[],r=e;for(let t=0;t<e.length;++t)n.push(Va.tidy((()=>{let e=r[t];if(t>0)for(let r=0;r<t;++r){const t=Go(Nh(Go(n[r],e)),n[r]);e=du(e,t)}return Vo(e,Th(e,"euclidean"))})));return t?yd(n,0):n}});function Af(e,t=!1){return Va.tidy((()=>{ie(2===e.shape.length,(()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`));const n=e.shape[0],r=e.shape[1];let s=Oh(n),a=zo(e);const i=kd([[1]],[1,1]);let o=zo(i);const u=n>=r?r:n;for(let e=0;e<u;++e){const t=a,u=o,l=s;[o,a,s]=Va.tidy((()=>{const t=Tc(a,[e,e],[n-e,1]),u=Th(t),l=Tc(a,[e,e],[1,1]),c=oh(Dh(l,0),kd([[-1]]),kd([[1]])),h=du(l,Go(c,u)),p=Vo(t,h);o=1===p.shape[0]?zo(i):Nc([i,Tc(p,[1,0],[p.shape[0]-1,p.shape[1]])],0);const d=Xu(Vo(Hu(c,h),u)),f=Tc(a,[e,0],[n-e,r]),m=Go(d,o),g=Ju(o);if(0===e)a=du(f,Hu(m,Hu(g,f)));else{const t=du(f,Hu(m,Hu(g,f)));a=Nc([Tc(a,[0,0],[e,r]),t],0)}const y=Ju(m),b=Tc(s,[0,e],[n,s.shape[1]-e]);if(0===e)s=du(b,Hu(Hu(b,o),y));else{const t=du(b,Hu(Hu(b,o),y));s=Nc([Tc(s,[0,0],[n,e]),t],1)}return[o,a,s]})),vi([t,u,l])}return!t&&n>r&&(s=Tc(s,[0,0],[n,r]),a=Tc(a,[0,0],[r,r])),[s,a]}))}const Rf=ai({qr_:function(e,t=!1){if(ie(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return Af(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),r=Rd(vc(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),s=[],a=[];return r.forEach((e=>{const[n,r]=Af(e,t);s.push(n),a.push(r)})),[vc(yd(s,0),e.shape),vc(yd(a,0),e.shape)]}}});var Of;!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(Of||(Of={}));const Ff=ai({computeWeightedLoss_:function(e,t,n=Of.SUM_BY_NONZERO_WEIGHTS){const r=ti(e,"losses","computeWeightedLoss");let s=null;null!=t&&(s=ti(t,"weights","computeWeightedLoss"));const a=null==s?r:Go(r,s);if(n===Of.NONE)return a;if(n===Of.SUM)return Nh(a);if(n===Of.MEAN){if(null==s)return op(a);{const e=r.size/s.size,t=Vo(Nh(a),Nh(s));return e>1?Vo(t,tu(e)):t}}if(n===Of.SUM_BY_NONZERO_WEIGHTS){if(null==s)return Vo(Nh(a),tu(r.size));{const e=Go(s,lp(r.shape)),t=Lo(Nh(yp(e,tu(0))),"float32");return Vo(Nh(a),t)}}throw Error(`Unknown reduction: ${n}`)}}),_f=ai({absoluteDifference_:function(e,t,n,r=Of.SUM_BY_NONZERO_WEIGHTS){const s=ti(e,"labels","absoluteDifference"),a=ti(t,"predictions","absoluteDifference");let i=null;null!=n&&(i=ti(n,"weights","absoluteDifference")),oe(s.shape,a.shape,"Error in absoluteDifference: ");const o=mu(du(s,a));return Ff(o,i,r)}}),Df=ai({cosineDistance_:function(e,t,n,r,s=Of.SUM_BY_NONZERO_WEIGHTS){const a=ti(e,"labels","cosineDistance"),i=ti(t,"predictions","cosineDistance");let o=null;null!=r&&(o=ti(r,"weights","cosineDistance")),oe(a.shape,i.shape,"Error in cosineDistance: ");const u=tu(1),l=du(u,Nh(Go(a,i),n,!0));return Ff(l,o,s)}}),Mf=ai({hingeLoss_:function(e,t,n,r=Of.SUM_BY_NONZERO_WEIGHTS){let s=ti(e,"labels","hingeLoss");const a=ti(t,"predictions","hingeLoss");let i=null;null!=n&&(i=ti(n,"weights","hingeLoss")),oe(s.shape,a.shape,"Error in hingeLoss: ");const o=tu(1);s=du(Go(tu(2),s),o);const u=Gp(du(o,Go(s,a)));return Ff(u,i,r)}}),Lf=ai({huberLoss_:function(e,t,n,r=1,s=Of.SUM_BY_NONZERO_WEIGHTS){const a=ti(e,"labels","huberLoss"),i=ti(t,"predictions","huberLoss");let o=null;null!=n&&(o=ti(n,"weights","huberLoss")),oe(a.shape,i.shape,"Error in huberLoss: ");const u=tu(r),l=mu(du(i,a)),c=hp(l,u),h=du(l,c),p=Wo(Go(tu(.5),Ho(c)),Go(u,h));return Ff(p,o,s)}}),zf=ai({logLoss_:function(e,t,n,r=1e-7,s=Of.SUM_BY_NONZERO_WEIGHTS){const a=ti(e,"labels","logLoss"),i=ti(t,"predictions","logLoss");let o=null;null!=n&&(o=ti(n,"weights","logLoss")),oe(a.shape,i.shape,"Error in logLoss: ");const u=tu(1),l=tu(r),c=Xu(Go(a,jh(Wo(i,l)))),h=Go(du(u,a),jh(Wo(du(u,i),l))),p=du(c,h);return Ff(p,o,s)}}),Pf=ai({meanSquaredError_:function(e,t,n,r=Of.SUM_BY_NONZERO_WEIGHTS){const s=ti(e,"labels","meanSquaredError"),a=ti(t,"predictions","meanSquaredError");let i=null;null!=n&&(i=ti(n,"weights","meanSquaredError")),oe(s.shape,a.shape,"Error in meanSquaredError: ");const o=md(s,a);return Ff(o,i,r)}}),Bf=ai({sigmoidCrossEntropy_:function(e,t,n,r=0,s=Of.SUM_BY_NONZERO_WEIGHTS){let a=ti(e,"multiClassLabels","sigmoidCrossEntropy");const i=ti(t,"logits","sigmoidCrossEntropy");let o=null;if(null!=n&&(o=ti(n,"weights","sigmoidCrossEntropy")),oe(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=tu(r),t=tu(1),n=tu(.5);a=Wo(Go(a,du(t,e)),Go(n,e))}const u=function(e,t){const n=ti(e,"labels","sigmoidCrossEntropyWithLogits"),r=ti(t,"logits","sigmoidCrossEntropyWithLogits");oe(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const s=Gp(r),a=Go(r,n),i=Hh($h(Xu(mu(r))));return Wo(du(s,a),i)}(a,i);return Ff(u,o,s)}}),Wf=ai({softmaxCrossEntropy_:function(e,t,n,r=0,s=Of.SUM_BY_NONZERO_WEIGHTS){let a=ti(e,"onehotLabels","softmaxCrossEntropy");const i=ti(t,"logits","softmaxCrossEntropy");let o=null;if(null!=n&&(o=ti(n,"weights","softmaxCrossEntropy")),oe(a.shape,i.shape,"Error in softmaxCrossEntropy: "),r>0){const e=tu(r),t=tu(1),n=tu(a.shape[1]);a=Wo(Go(a,du(t,e)),Vo(e,n))}const u=function(e,t,n=-1){if(-1===n&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);const r=Qo(((e,t,r)=>{const s=Yh(t,[n],!0),a=du(Lo(t,"float32"),s);r([e,a]);const i=Xu(Go(a,e));return{value:Nh(i,[n]),gradFunc:(e,t)=>{const[r,s]=t,a=yh(e.shape,[n]);return[Go(vc(e,a),du(Lo(r,"float32"),$h(s))),Go(vc(e,a),du($h(s),Lo(r,"float32")))]}}}));return r(e,t)}(a,i);return Ff(u,o,s)}}),Uf=ai({sparseFillEmptyRows_:function(e,t,n,r){const s=ti(e,"indices","sparseFillEmptyRows","int32"),a=ti(t,"values","sparseFillEmptyRows"),i=ti(n,"denseShape","sparseFillEmptyRows","int32"),o=ti(r,"defaultValue","sparseFillEmptyRows",a.dtype);if(2!==s.rank)throw new Error(`Indices should be Tensor2D but received shape\n ${s.shape}`);if(1!==a.rank)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(1!==i.rank)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(0!==o.rank)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);const u={indices:s,values:a,denseShape:i,defaultValue:o},l=Va.runKernel(jr,u);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}}),Vf=ai({sparseReshape_:function(e,t,n){const r=ti(e,"inputIndices","sparseReshape","int32"),s=ti(t,"inputShape","sparseReshape","int32"),a=ti(n,"newShape","sparseReshape","int32");if(2!==r.rank)throw new Error(`Input indices should be Tensor2D but received shape\n ${r.shape}`);if(1!==s.rank)throw new Error(`Input shape should be Tensor1D but received shape ${s.shape}`);if(1!==a.rank)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);const i={inputIndices:r,inputShape:s,newShape:a},o=Va.runKernel(Hr,i);return{outputIndices:o[0],outputShape:o[1]}}}),Gf=ai({sparseSegmentMean_:function(e,t,n){const r=ti(e,"data","sparseSegmentMean"),s=ti(t,"indices","sparseSegmentMean","int32"),a=ti(n,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${s.shape}`);if(1!==a.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${a.shape}`);const i={data:r,indices:s,segmentIds:a};return Va.runKernel(qr,i)}}),jf=ai({sparseSegmentSum_:function(e,t,n){const r=ti(e,"data","sparseSegmentSum"),s=ti(t,"indices","sparseSegmentSum","int32"),a=ti(n,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${s.shape}`);if(1!==a.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${a.shape}`);const i={data:r,indices:s,segmentIds:a};return Va.runKernel(Kr,i)}}),Hf=ai({stringNGrams_:function(e,t,n,r,s,a,i,o){const u=ti(e,"data","stringNGrams","string");if("string"!==u.dtype)throw new Error("Data must be of datatype string");if(1!==u.shape.length)throw new Error(`Data must be a vector, saw: ${u.shape}`);const l=ti(t,"dataSplits","stringNGrams");if("int32"!==l.dtype)throw new Error("Data splits must be of datatype int32");const c={separator:n,nGramWidths:r,leftPad:s,rightPad:a,padWidth:i,preserveShortSequences:o},h={data:u,dataSplits:l},p=Va.runKernel(es,h,c);return{nGrams:p[0],nGramsSplits:p[1]}}}),qf=ai({stringSplit_:function(e,t,n=!0){const r=ti(e,"input","stringSplit","string"),s=ti(t,"delimiter","stringSplit","string");if(1!==r.rank)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(0!==s.rank)throw new Error(`Delimiter should be a scalar but received shape ${s.shape}`);const a={skipEmpty:n},i={input:r,delimiter:s},o=Va.runKernel(ts,i,a);return{indices:o[0],values:o[1],shape:o[2]}}}),Kf=ai({stringToHashBucketFast_:function(e,t){const n=ti(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");const s={input:n};return Va.runKernel(ns,s,r)}}),Xf=ai({staticRegexReplace_:function(e,t,n,r=!0){const s=ti(e,"input","staticRegexReplace","string"),a={pattern:t,rewrite:n,replaceGlobal:r};return Va.runKernel(Zr,{x:s},a)}}),Yf={fft:cd,ifft:hd,rfft:fd,irfft:pd},Jf={hammingWindow:tf,hannWindow:nf,frame:rf,stft:sf},Zf={flipLeftRight:of,grayscaleToRGB:uf,resizeNearestNeighbor:Sf,resizeBilinear:Nf,rgbToGrayscale:lf,rotateWithOffset:cf,cropAndResize:af,nonMaxSuppression:pf,nonMaxSuppressionAsync:async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){const a=ti(e,"boxes","nonMaxSuppressionAsync"),i=ti(t,"scores","nonMaxSuppressionAsync"),o=hf(a,i,n,r,s);n=o.maxOutputSize,r=o.iouThreshold,s=o.scoreThreshold;const u=await Promise.all([a.data(),i.data()]),l=u[0],c=u[1],{selectedIndices:h}=mf(l,c,n,r,s);return a!==e&&a.dispose(),i!==t&&i.dispose(),vd(h,"int32")},nonMaxSuppressionWithScore:kf,nonMaxSuppressionWithScoreAsync:async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=0){const i=ti(e,"boxes","nonMaxSuppressionAsync"),o=ti(t,"scores","nonMaxSuppressionAsync"),u=hf(i,o,n,r,s,a);n=u.maxOutputSize,r=u.iouThreshold,s=u.scoreThreshold,a=u.softNmsSigma;const l=await Promise.all([i.data(),o.data()]),c=l[0],h=l[1],{selectedIndices:p,selectedScores:d}=yf(c,h,n,r,s,a);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:vd(p,"int32"),selectedScores:vd(d)}},nonMaxSuppressionPadded:If,nonMaxSuppressionPaddedAsync:async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){const i=ti(e,"boxes","nonMaxSuppressionAsync"),o=ti(t,"scores","nonMaxSuppressionAsync"),u=hf(i,o,n,r,s,null),l=u.maxOutputSize,c=u.iouThreshold,h=u.scoreThreshold,[p,d]=await Promise.all([i.data(),o.data()]),{selectedIndices:f,validOutputs:m}=gf(p,d,l,c,h,a);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:vd(f,"int32"),validOutputs:tu(m,"int32")}},threshold:Tf,transform:Cf},Qf={bandPart:$f,gramSchmidt:Ef,qr:Rf},em={absoluteDifference:_f,computeWeightedLoss:Ff,cosineDistance:Df,hingeLoss:Mf,huberLoss:Lf,logLoss:zf,meanSquaredError:Pf,sigmoidCrossEntropy:Bf,softmaxCrossEntropy:Wf},tm={sparseFillEmptyRows:Uf,sparseReshape:Vf,sparseSegmentMean:Gf,sparseSegmentSum:jf},nm={stringNGrams:Hf,stringSplit:qf,stringToHashBucketFast:Kf,staticRegexReplace:Xf},rm=ql,sm="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();function am(){return new Promise((e=>sm((()=>e()))))}function im(e,t){const n=e[0].length;e.forEach(((e,t)=>{ie(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`))})),ie(t>=0&&t<n,(()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`));const r=e[0];e.forEach(((e,s)=>{for(let a=0;a<n;a++)ie(a===t||e[a]===r[a],(()=>`Error in concat${n}D: Shape of tensors[${s}] (${e}) does not match the shape of the rest (${r}) along the non-concatenated axis ${s}.`))}))}function om(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}var um;function lm(e,t,n){let r=new Array;if(null==n&&null==t)return r;if(null==t)for(;r.length<e+n.length;)r.push(-1);else r=t.slice();if(null==n)return r;if(e+n.length!==r.length)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.rank = ${e+n.length}, but shape.rank = ${r.length}`);for(let s=1;s<n.length;++s){const a=n[s],i=r[r.length-n.length+s],o=r[i];if(a>=0)if(o>=0){if(o!==a)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${s+e}] = ${a} but shape[${s+e}] = ${o}`)}else r[i]=a}return r}function cm(e){const t={FIRST_DIM_SIZE:um.FIRST_DIM_SIZE,VALUE_ROWIDS:um.VALUE_ROWIDS,ROW_LENGTHS:um.ROW_LENGTHS,ROW_SPLITS:um.ROW_SPLITS,ROW_LIMITS:um.ROW_LIMITS,ROW_STARTS:um.ROW_STARTS},n=[];for(const r of e){if(!(r in t))break;n.push(t[r])}return n}function hm(e){return 0===e.length?0:e[0]===um.FIRST_DIM_SIZE?e.length-1:e.length}function pm(e,t){if(null==e||null==t)return;const n=e.length,r=t.length;if(n>=r)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${n} must be less than ragged tensor input flatValues.rank = ${r})`);for(let s=0;s<Math.min(n,r-1);++s){const n=e[s],r=t[s+1];if(n>=0&&r>=0&&1!==n&&n!==r)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${s-e.length}] = ${n} but ragged tensor input.flatValues.shape[${s-e.length}] = ${r}`)}}!function(e){e[e.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",e[e.VALUE_ROWIDS=1]="VALUE_ROWIDS",e[e.ROW_LENGTHS=2]="ROW_LENGTHS",e[e.ROW_SPLITS=3]="ROW_SPLITS",e[e.ROW_LIMITS=4]="ROW_LIMITS",e[e.ROW_STARTS=5]="ROW_STARTS"}(um||(um={}));const dm=30;function fm(e){return e<=dm?e:_e(e,Math.floor(Math.sqrt(e)))}function mm(e,t,n){return[n*("number"==typeof e?e:e[0]),t*("number"==typeof e?e:e[1])]}function gm(e,t,n,r=!0){let s=[];if(r)s=s.concat(t.slice(0)),s.push(e[0]/n),s=s.concat(e.slice(1));else{s=s.concat(e[0]);const n=t.length;for(let r=0;r<n;++r)s=s.concat([e[r+1]/t[r],t[r]]);s=s.concat(e.slice(n+1))}return s}function ym(e,t,n=!0){const r=[];if(n){r.push(t);for(let n=t+1;n<e;++n)n<=2*t?(r.push(n),r.push(n-(t+1))):r.push(n)}else{const n=[],s=[];for(let r=1;r<e;++r)r>=2*t+1||r%2==1?s.push(r):n.push(r);r.push(...n),r.push(0),r.push(...s)}return r}function bm(e,t,n,r=!0){const s=[];r?s.push(e[0]/n):s.push(e[0]*n);for(let n=1;n<e.length;++n)n<=t.length?r?s.push(t[n-1]*e[n]):s.push(e[n]/t[n-1]):s.push(e[n]);return s}function xm(e,t){const n=[0];for(let r=0;r<t;++r)n.push(e[r][0]);return n}function wm(e,t,n){const r=e.slice(0,1);for(let s=0;s<n;++s)r.push(e[s+1]-t[s][0]-t[s][1]);return r}const vm=1.7580993408473768,km=1.0507009873554805,Im=.3275911,Nm=.254829592,Sm=-.284496736,Tm=1.421413741,Cm=-1.453152027,$m=1.061405429;function Em(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(2*e.length);for(let r=0;r<n.length;r+=2)n[r]=e[r/2],n[r+1]=t[r/2];return n}function Am(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=e[r],n[r/2]=e[r+1];return{real:t,imag:n}}function Rm(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let t=0;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],r[Math.floor(t/4)]=e[t+1];return{real:n,imag:r}}function Om(e){const t=Math.floor(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let t=2;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],r[Math.floor(t/4)]=e[t+1];return{real:n,imag:r}}function Fm(e,t){return{real:e[2*t],imag:e[2*t+1]}}function _m(e,t,n,r){e[2*r]=t,e[2*r+1]=n}function Dm(e,t){const n=new Float32Array(e/2),r=new Float32Array(e/2);for(let s=0;s<Math.ceil(e/2);s++){const a=(t?2:-2)*Math.PI*(s/e);n[s]=Math.cos(a),r[s]=Math.sin(a)}return{real:n,imag:r}}function Mm(e,t,n){const r=(n?2:-2)*Math.PI*(e/t);return{real:Math.cos(r),imag:Math.sin(r)}}const Lm="->",zm=/->/g,Pm=",",Bm="...";function Wm(e,t){const n=((e=e.replace(/\s/g,"")).length-e.replace(zm,"").length)/Lm.length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error(`Equation must contain exactly one arrow ("${Lm}").`);const[r,s]=e.split(Lm);ie(-1===r.indexOf(Bm),(()=>`The ellipsis notation ("${Bm}") is not supported yet.`));const a=r.split(Pm),i=a.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const o=[];for(let e=0;e<s.length;++e){const t=s[e];if(!a.some((e=>-1!==e.indexOf(t))))throw new Error(`Output subscripts contain the label ${t} not present in the input subscripts.`);-1===o.indexOf(t)&&o.push(t)}for(let e=0;e<r.length;++e){const t=r[e];-1===o.indexOf(t)&&t!==Pm&&o.push(t)}const u=new Array(a.length);for(let e=0;e<i;++e){if(new Set(a[e].split("")).size!==a[e].length)throw new Error(`Found duplicate axes in input component ${a[e]}. Support for duplicate axes in input is not implemented yet.`);u[e]=[];for(let t=0;t<a[e].length;++t)u[e].push(o.indexOf(a[e][t]))}const l=o.length,c=[];for(let e=s.length;e<l;++e)c.push(e);return{allDims:o,summedDims:c,idDims:u}}function Um(e,t){let n=new Array(e);n.fill(-1);for(let e=0;e<t.length;++e)n[t[e]]=e;const r=[];for(let t=0;t<e;++t)-1===n[t]&&r.push(t);return n=n.filter((e=>-1!==e)),{permutationIndices:n,expandDims:r}}function Vm(e,t,n){const r=new Array(e);for(let e=0;e<n.length;++e){const s=n[e].shape;for(let n=0;n<t[e].length;++n)void 0===r[t[e][n]]?r[t[e][n]]=s[n]:ie(r[t[e][n]]===s[n],(()=>`Expected dimension ${r[t[e][n]]} at axis ${n} of input shaped ${JSON.stringify(s)}, but got dimension ${s[n]}`))}}function Gm(e,t){const n=e,r=[];let s=0;0===e.length&&n.push(-1),s=e.length+1;for(let e=0;e<s;++e)r.push([]);const a=[];for(let e=0;e<n.length;++e){const s=Hm(t,n[e]);for(const t of s)-1===a.indexOf(t)&&(r[e].push(t),a.push(t))}return{path:n,steps:r}}function jm(e){return e.every(((e,t)=>e===t))}function Hm(e,t){const n=[];for(let r=0;r<e.length;++r)0!==e[r].length&&-1===e[r].indexOf(t)&&-1!==t||n.push(r);return n}function qm(e,t,n=0){let r=[];if("number"==typeof t)ie(e.shape[n]%t==0,(()=>"Number of splits must evenly divide the axis.")),r=new Array(t).fill(e.shape[n]/t);else{const s=t.reduce(((e,t)=>(-1===t&&(e+=1),e)),0);ie(s<=1,(()=>"There should be only one negative value in split array."));const a=t.indexOf(-1);if(-1!==a){const r=t.reduce(((e,t)=>t>0?e+t:e));t[a]=e.shape[n]-r}ie(e.shape[n]===t.reduce(((e,t)=>e+t)),(()=>"The sum of sizes must match the size of the axis dimension.")),r=t}return r}function Km(e){return`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${e}`}function Xm(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function Ym(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function Jm(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function Zm(e,t){return`size ${e} must be non-negative, not ${t}`}function Qm(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function eg(e,t){return`Input to reshape is a SparseTensor with ${le(e)}\n dense values, but the requested shape requires a multiple of ${le(t)}. inputShape=${e} outputShape= ${t}`}function tg(e,t){return`Input to reshape is a tensor with ${le(e)} dense values, but the requested shape has ${le(t)}. inputShape=${e} outputShape=${t}`}function ng(){return"segment ids must be >= 0"}function rg(){return"segment ids are not increasing"}function sg(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function ag(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}function ig(e,t){let n,r=!1;for(e<=dm?(n=e,r=!0):n=_e(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=_e(e,n+1);return n}function og(e,t,n){const r=[],s=e.length;for(let a=0;a<s;a++)a!==t?r.push(e[a]):r.push(n);return r}function ug(e,t,n,r){const s=t.shape.length,a=e.shape.length;if(0!==r&&(r<-s||r>s))throw new Error(`Expect batchDims in the range of [-${s}, ${s}], but got ${r}`);if(r<0&&(r+=s),r>a)throw new Error(`batchDims (${r}) must be less than rank(x) (\n ${a}).`);if(n<r)throw new Error(`batchDims (${r}) must be less than or equal to axis (${n}).`);for(let n=0;n<r;++n)if(e.shape[n]!==t.shape[n])throw new Error(`x.shape[${n}]: ${e.shape[n]} should be equal to indices.shape[${n}]: ${t.shape[n]}.`);const i=e.shape[n],o=[];let u=1,l=1,c=1;for(let t=0;t<r;++t)o.push(e.shape[t]),u*=e.shape[t];for(let t=r;t<n;t++)o.push(e.shape[t]),l*=e.shape[t];for(let e=r;e<s;e++)o.push(t.shape[e]);for(let t=n+1;t<a;t++)o.push(e.shape[t]),c*=e.shape[t];return{batchSize:u,sliceSize:c,outerSize:l,dimSize:i,outputShape:o}}function lg(e){try{return e.map((e=>ta(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function cg(e){return e.map((e=>ea(e)))}!function(){for(const e of Nu)iu(e)}();const hg={kernelName:nt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Go(e,bd(Lo(n,"float32"),-1))}}},pg={kernelName:rt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Ho(Lo(n,"float32")),r=jo(du(tu(1),t));return Xu(Vo(e,r))}}}},dg={kernelName:st,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=jo(du(Ho(Lo(n,"float32")),1));return Vo(e,t)}}}},fg={kernelName:at,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=bu(n.shape,r.shape);return{a:()=>{let t=e;const r=yu(n.shape,s);return r.length>0&&(t=Nh(t,r)),vc(t,n.shape)},b:()=>{let t=e;const n=yu(r.shape,s);return n.length>0&&(t=Nh(t,n)),vc(t,r.shape)}}}},mg={kernelName:it,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach(((t,r)=>{n[r]=()=>e.clone()})),n}},gg={kernelName:lt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>qo(n)}}},yg={kernelName:ct,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>qo(n)}}},bg={kernelName:ht,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Vo(e,jo(du(tu(1),Ho(Lo(n,"float32")))))}}},xg={kernelName:pt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=jo(Wo(tu(1),Ho(Lo(n,"float32"))));return Vo(e,t)}}}},wg={kernelName:mt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=bu(n.shape,r.shape);return{a:()=>{const t=Wo(Ho(n),Ho(r));let a=Go(e,Vo(r,t));const i=yu(n.shape,s);return i.length>0&&(a=Nh(a,i)),vc(a,n.shape)},b:()=>{const t=Wo(Ho(n),Ho(r));let a=Xu(Go(e,Vo(n,t)));const i=yu(r.shape,s);return i.length>0&&(a=Nh(a,i)),vc(a,r.shape)}}}},vg={kernelName:dt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Vo(e,Wo(Ho(Lo(n,"float32")),1))}}},kg={kernelName:ft,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Vo(e,du(tu(1),Ho(Lo(n,"float32"))))}}},Ig=ai({avgPool3dGrad_:function(e,t,n,r,s,a){const i=ti(e,"dy","avgPool3dGrad"),o=ti(t,"input","avgPool3dGrad");let u=i,l=o,c=!1;4===o.rank&&(c=!0,u=vc(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),l=vc(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),ie(5===u.rank,(()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`)),ie(5===l.rank,(()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${l.rank}.`)),wc("avgPool3dGrad",s,a);const h={dy:u,input:l},p={filterSize:n,strides:r,pad:s,dimRoundingMode:a},d=Va.runKernel(xt,h,p);return c?vc(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}),Ng={kernelName:bt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:s,strides:a,pad:i,dimRoundingMode:o}=n;return{x:()=>Ig(e,r,s,a,i,o)}}},Sg=ai({avgPoolGrad_:function(e,t,n,r,s){const a=ti(e,"dy","avgPoolGrad"),i=ti(t,"input","avgPoolGrad");ie(i.rank===a.rank,(()=>`Rank of input (${i.rank}) does not match rank of dy (${a.rank})`));let o=i,u=a,l=!1;3===i.rank&&(l=!0,o=vc(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=vc(a,[1,a.shape[0],a.shape[1],a.shape[2]])),ie(4===u.rank,(()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${u.rank}.`)),ie(4===o.rank,(()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`));const c={dy:u,input:o},h={filterSize:n,strides:r,pad:s},p=Va.runKernel(yt,c,h);return l?vc(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),Tg={kernelName:gt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:s,strides:a,pad:i}=n;return{x:()=>Sg(e,r,s,a,i)}}},Cg={kernelName:wt,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[r,s]=t,{transposeA:a,transposeB:i}=n;return a||i?!a&&i?{a:()=>Hu(e,s,!1,!1),b:()=>Hu(e,r,!0,!1)}:a&&!i?{a:()=>Hu(s,e,!1,!0),b:()=>Hu(r,e,!1,!1)}:{a:()=>Hu(s,e,!0,!0),b:()=>Hu(e,r,!0,!0)}:{a:()=>Hu(e,s,!1,!0),b:()=>Hu(r,e,!0,!1)}}},$g={kernelName:vt,gradFunc:(e,t,n)=>{const{blockShape:r,crops:s}=n;return{x:()=>Sp(e,r,s)}}},Eg={kernelName:Nt,gradFunc:(e,t,n)=>{const r=n,s=r.inputShape,a=r.shape,i=Array.from(a);for(let e=s.length-1;e>=0;e--)if(s[e]===a[e])i[e]=1;else if(1!==s[e])throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${a}].`);const o=[];for(let e=0;e<i.length;e++)i[e]>1&&o.push(e);return{x:()=>Nh(e,o,!0)}}},Ag={kernelName:Tt,gradFunc:e=>({x:()=>e.clone()})},Rg={kernelName:Ct,gradFunc:e=>({x:()=>qo(e)})},Og={kernelName:$t,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{clipValueMin:s,clipValueMax:a}=n;return{x:()=>oh(Jh(Mh(r,s),Uh(r,a)),e,qo(e))}}},Fg={kernelName:At,inputsToSave:["x"],gradFunc:hg.gradFunc},_g={kernelName:Rt,saveAllInputs:!0,gradFunc:(e,t,n)=>{const r=t.map((e=>e.shape)),{axis:s}=n,a=we(s,t[0].shape)[0],i=r.map((e=>e[a]));return dd(e,i,a).map((e=>()=>e))}},Dg={kernelName:Ot,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,s]=t,{dilations:a,strides:i,pad:o,dataFormat:u}=n;return ie(gc(a),(()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`)),{x:()=>Hc(r.shape,e,s,i,o,u),filter:()=>jd(r,e,s.shape,i,o,u)}}},Mg={kernelName:_t,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[r,s]=t,{strides:a,pad:i,dataFormat:o,dimRoundingMode:u}=n;return{dy:()=>Gc(e,s,a,i,o,1,u),filter:()=>jd(e,r,s.shape,a,i,o,u)}}},Lg=ai({conv3DBackpropFilter_:function(e,t,n,r,s){let a=e;4===e.rank&&(a=vc(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;4===i.rank&&(i=vc(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),ie(5===a.rank,(()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`)),ie(5===i.rank,(()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`)),ie(5===n.length,(()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`)),ie(a.shape[4]===n[3],(()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`)),ie(i.shape[4]===n[4],(()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${n[4]}).`));const o={x:a,dy:i},u={strides:r,pad:s,filterShape:n};return Va.runKernel(Mt,o,u)}}),zg={kernelName:Dt,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:s,pad:a}=n;ie(gc(r),(()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`));const[i,o]=t;return{x:()=>Xc(i.shape,e,o,s,a),filter:()=>Lg(i,e,o.shape,s,a)}}},Pg={kernelName:zt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Go(Xu(rd(Lo(n,"float32"))),e)}}},Bg={kernelName:Pt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Go(sd(Lo(n,"float32")),e)}}},Wg={kernelName:Wt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{axis:s,exclusive:a,reverse:i}=n;return{x:()=>{const t=xh([s],r.rank);let n=eh(e,s,a,!i);return null!=t&&(n=Ju(n,t)),n}}}},Ug={kernelName:jt,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:s,pad:a,dimRoundingMode:i}=n,o=null==r?[1,1]:r;ie(gc(o),(()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`));const[u,l]=t;return ie(4===u.rank,(()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${u.rank}.`)),ie(4===l.rank,(()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${l.rank}.`)),ie(u.shape[3]===l.shape[2],(()=>`Error in gradient of depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`)),ie(yc(s,o),(()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'.`)),wc("depthwiseConv2d",a,i),{x:()=>Zd(u.shape,e,l,s,a,o,i),filter:()=>Jd(u,e,l.shape,s,a,o,i)}}},Vg={kernelName:Xt,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,s]=t,a={x:r,filter:s,dy:e},i={x:r,filter:s,dy:e};return{x:()=>Va.runKernel(Yt,a,n),filter:()=>Va.runKernel(Jt,i,n)}}},Gg={kernelName:tn,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,r={dy:e,y:n};return{x:()=>Va.runKernel(nn,r)}}},jg={kernelName:rn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=Go($h(Xu(Ho(n))),2/Math.sqrt(Math.PI));return{x:()=>Go(e,r)}}},Hg={kernelName:an,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Go(e,n)}}},qg={kernelName:on,inputsToSave:["input"],gradFunc:(e,t)=>{const[n]=t;return{input:()=>vc(e,n.shape)}}},Kg={kernelName:un,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Go(e,$h(n))}}},Xg={kernelName:pn,gradFunc:e=>({x:()=>qo(e)})},Yg={kernelName:dn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=bu(n.shape,r.shape);return{a:()=>{const t=Vo(e,Lo(r,"float32")),a=yu(n.shape,s);return a.length>0?vc(Nh(t,a),n.shape):t},b:()=>{let t=Go(e,Lo(n,"float32"));const a=yu(r.shape,s);a.length>0&&(t=vc(Nh(t,a),r.shape));const i=Ho(r);return Xu(Vo(t,Lo(i,"float32")))}}}},Jg={kernelName:fn,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:r}=n,[s,a,i,o]=t,u=null==o?tu(1):o,l=yu(a.shape,s.shape),c=[];if(1===a.rank){for(let e=0;e<s.shape.length-1;++e)c.push(s.shape[e]);c.push(1)}const h=du(s,a),p=Go(e,u),d=Zp(Wo(i,tu(r))),f=Go(Go(Go(d,d),d),tu(-.5));return{x:()=>1===a.rank?vc(Go(Go(e,Rh(vc(d,[1,1,1,a.shape[0]]),c)),u),s.shape):vc(Go(Go(e,d),u),s.shape),mean:()=>{let e=Go(Go(d,tu(-1)),p);return 1===a.rank&&(e=Nh(e,l)),vc(e,a.shape)},variance:()=>{let e=Go(Go(f,h),p);return 1===a.rank&&(e=Nh(e,l)),vc(e,a.shape)},scale:()=>{const t=Go(h,d);let n=Go(e,t);return 1===a.rank&&(n=Nh(n,l)),vc(n,a.shape)},offset:()=>{let t=e;return 1===a.rank&&(t=Nh(t,l)),vc(t,a.shape)}}}},Zg={kernelName:mn,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[r,s]=t,{axis:a,batchDims:i}=n,o=we(a,r.shape)[0],u=(e,t,n)=>()=>{const r=e.shape,s=t.size,i=r.slice(0,o),u=i.length,l=r.slice(a,r.length).slice(1),c=l.length,h=Qg(0,u),p=Qg(u+1,u+1+c),d=ey([i,[s],l]),f=vc(n,d),m=vc(t,[s]),g=ey([[u],h,p]),y=Ju(f,g);let b=Ad(y,m,e.shape[o]);const x=wh(g);return b=Ju(b,x),b};if(1===i){const t=r.shape[0],n=r.split(t,0);return{x:()=>{const t=yd(n.map(((t,n)=>u(t,s.slice(n,1),e.slice(n,1))())));return t.reshape(r.shape)},indices:()=>s}}return{x:u(r,s,e),indices:()=>s}}};function Qg(e,t){const n=[];for(let r=e;r<t;++r)n.push(r);return n}function ey(e){const t=[];for(let n=0;n<e.length;++n)for(let r=0;r<e[n].length;++r)t.push(e[n][r]);return t}const ty={kernelName:bn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t;return{a:()=>qo(n),b:()=>qo(r)}}},ny={kernelName:xn,gradFunc:e=>({x:()=>Lo(e,"float32")})},ry={kernelName:kn,gradFunc:e=>({x:()=>qo(e)})},sy={kernelName:In,gradFunc:e=>({x:()=>qo(e)})},ay={kernelName:Nn,gradFunc:e=>({x:()=>qo(e)})},iy={kernelName:Sn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{alpha:s}=n,a=Dh(r,0);return{x:()=>oh(a,e,Go(e,s))}}},oy={kernelName:An,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Vo(e,Wo(n,1))}}},uy={kernelName:En,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Vo(e,Lo(n,"float32"))}}},ly={kernelName:Dn,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{axis:s}=n;return{logits:()=>{const t=$h(r);return du(e,Go(Nh(e,s,!0),t))}}}},cy=ai({localResponseNormalizationBackprop_:function(e,t,n,r=5,s=1,a=1,i=.5){const o={x:e,y:t,dy:n},u={depthRadius:r,bias:s,alpha:a,beta:i};return Va.runKernel(zn,o,u)}}),hy={kernelName:Ln,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,s]=t,{depthRadius:a,bias:i,alpha:o,beta:u}=n;return{x:()=>cy(r,s,e,a,i,o,u)}}};function py(e,t,n,r){return t.rank<n.rank&&(t=vc(t,yh(t.shape,r))),e.rank<n.rank&&(e=vc(e,yh(e.shape,r))),{x:()=>Go(e,Lo(ih(n,t),e.dtype))}}const dy={kernelName:Bn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{reductionIndices:s}=r,a=t[0],i=py(e,t[1],a,we(s,a.shape));return{x:()=>i.x()}}},fy={kernelName:Wn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t;return{a:()=>Go(e,Lo(Mh(n,r),"float32")),b:()=>Go(e,Lo(Wh(n,r),"float32"))}}},my=ai({maxPool3dGrad_:function(e,t,n,r,s,a,i){const o=ti(e,"dy","maxPool3dGrad"),u=ti(t,"input","maxPool3dGrad"),l=ti(n,"output","maxPool3dGrad");let c=o,h=u,p=l,d=!1;4===u.rank&&(d=!0,c=vc(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),h=vc(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]]),p=vc(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),ie(5===c.rank,(()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`)),ie(5===h.rank,(()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`)),ie(5===p.rank,(()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`)),wc("maxPool3dGrad",a,i);const f={dy:c,input:h,output:p},m={filterSize:r,strides:s,pad:a,dimRoundingMode:i},g=Va.runKernel(jn,f,m);return d?vc(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}}),gy={kernelName:Gn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,s]=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:u}=n;return{x:()=>my(e,r,s,a,i,o,u)}}},yy=ai({maxPoolGrad_:function(e,t,n,r,s,a,i){const o=ti(e,"dy","maxPoolGrad"),u=ti(t,"input","maxPoolGrad"),l=ti(n,"output","maxPoolGrad");ie(u.rank===o.rank,(()=>`Rank of input (${u.rank}) does not match rank of dy (${o.rank})`)),ie(4===o.rank,(()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`)),ie(4===u.rank,(()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${u.rank}.`)),wc("maxPoolGrad",a,i);const c={dy:o,input:u,output:l},h={filterSize:r,strides:s,pad:a,dimRoundingMode:i};return Va.runKernel(Vn,c,h)}}),by={kernelName:Un,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,s]=t,{filterSize:a,strides:i,pad:o}=n;return{x:()=>yy(e,r,s,a,i,o)}}},xy={kernelName:Yn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const r=t[0],{paddings:s}=n,a=s.map((e=>e[0]));return{x:()=>Tc(e,a,r.shape)}}},wy={kernelName:ur,inputsToSave:["x"],gradFunc:(e,t,n)=>{const r=t[0],{paddings:s}=n,a=s.map((e=>e[0]));return{x:()=>Tc(e,a,r.shape)}}},vy={kernelName:cr,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,r,s]=t,a=n,i=r,o=bu(a.shape,i.shape);return{a:()=>{const t=Lo(i,"float32");let n=Go(e,Go(t,pu(a,du(t,tu(1)))));const r=yu(a.shape,o);return r.length>0&&(n=Nh(n,r)),vc(n,a.shape)},b:()=>{const t=Dh(a,0),n=oh(t,jh(a),qo(a));let r=Go(e,Go(s,n));const u=yu(i.shape,o);return u.length>0&&(r=Nh(r,u)),vc(r,i.shape)}}}};const ky={kernelName:Fr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Dh(n,tu(0)),r=tu(vm),s=tu(km),a=Go(e,s),i=Go(Go(e,r),$h(Lo(n,"float32")));return oh(t,a,i)}}}},Iy={kernelName:Ur,gradFunc:(e,t,n)=>{const{blockShape:r,paddings:s}=n;return{x:()=>Ec(e,r,s)}}},Ny={kernelName:Vr,gradFunc:(e,t,n)=>{const{axis:r}=n;return{x:()=>Nc(e,r)}}},Sy=[hg,pg,dg,fg,mg,gg,yg,bg,xg,wg,vg,kg,Ng,Tg,Cg,$g,Eg,Ag,Rg,Og,Fg,_g,Mg,Dg,zg,Pg,Bg,Wg,Ug,Vg,{kernelName:Qt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=bu(n.shape,r.shape);return{a:()=>{const t=Vo(e,Lo(r,"float32")),a=yu(n.shape,s);return a.length>0?vc(Nh(t,a),n.shape):t},b:()=>{let t=Go(e,Lo(n,"float32"));const a=yu(r.shape,s);a.length>0&&(t=vc(Nh(t,a),r.shape));const i=Ho(r);return Xu(Vo(t,Lo(i,"float32")))}}}},Gg,jg,Hg,qg,Kg,Yg,Xg,Jg,Zg,ty,ny,ry,sy,ay,iy,oy,uy,ly,hy,dy,dy,fy,gy,by,{kernelName:qn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{axis:s}=n,a=we(s,r.shape),i=le(gh(r.shape,a)[1]);return{x:()=>{const t=r.shape.slice();a.forEach((e=>{t[e]=1}));const n=vc(e,t);return Vo(Go(n,lp(r.shape,"float32")),i)}}}},{kernelName:Kn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{axis:s}=r,[a,i]=t,o=py(e,i,a,we(s,a.shape));return{x:()=>o.x()}}},{kernelName:Xn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t;return{a:()=>Go(e,Lo(Uh(n,r),"float32")),b:()=>Go(e,Lo(Dh(n,r),"float32"))}}},xy,{kernelName:Jn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=bu(n.shape,r.shape);return{a:()=>{const t=yu(n.shape,s);return t.length>0?vc(Nh(e,t),n.shape):e},b:()=>{const t=Go(e,Xu(Fh(Vo(n,r)))),a=yu(r.shape,s);return a.length>0?vc(Nh(t,a),r.shape):t}}}},{kernelName:Qn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=bu(n.shape,r.shape);return{a:()=>{const t=Go(e,Lo(r,"float32")),a=yu(n.shape,s);return a.length>0?vc(Nh(t,a),n.shape):t},b:()=>{const t=Go(e,Lo(n,"float32")),a=yu(r.shape,s);return a.length>0?vc(Nh(t,a),r.shape):t}}}},{kernelName:er,gradFunc:e=>({x:()=>Xu(e)})},{kernelName:ir,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>up(n.shape,"float32")}}},{kernelName:ar,gradFunc:e=>({x:()=>qo(e)})},{kernelName:or,saveAllInputs:!0,gradFunc:(e,t,n)=>{const{axis:r}=n;return Rd(e,r).map((e=>()=>e))}},wy,wy,vy,{kernelName:hr,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,r]=t,s=Dh(n,0);return{x:()=>oh(s,e,Go(e,r)),alpha:()=>{let t=oh(s,qo(e),Go(e,n));const a=yu(r.shape,e.shape);return a.length>0&&(t=Nh(t,a)),vc(t,r.shape)}}}},{kernelName:pr,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{axis:s}=n;let a=[];return a=null==s?r.shape.map(((e,t)=>t)):"number"==typeof s?[s]:s,{x:()=>function(e,t,n){const r=e.shape.length,s=r-n.length,a=xh(n,r);let i=e;null!=a&&(i=Ju(e,a));const o=i.shape.slice(),u=o.splice(r-n.length,n.length).reduce(((e,t)=>e*t),1);o.push(u);let l=function(e,t,n){const r=e.shape.slice();r[n]=1;const s=vc(t,r),a=Qc(e,n,!0,!1),i=Qc(e,n,!0,!0),o=Go(a,i);return Go(s,o)}(i.reshape(o),t,s);if(l=l.reshape(i.shape),null!=a){const e=wh(a);l=Ju(l,e)}return l}(r,e,a)}}},{kernelName:br,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Vo(e,Xu(Ho(n)))}}},{kernelName:Sr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=Go(Uh(n,6),bd(n));return{x:()=>Go(e,Lo(r,"float32"))}}},{kernelName:xr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Go(e,Lo(bd(n),"float32"))}}},{kernelName:wr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>vc(e,n.shape)}}},{kernelName:Ir,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,s={dy:e,images:r};return{images:()=>Va.runKernel(Nr,s,n)}}},{kernelName:vr,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,s={dy:e,images:r};return{images:()=>Va.runKernel(kr,s,n)}}},{kernelName:Tr,gradFunc:(e,t,n)=>{const{dims:r}=n,s=we(r,e.shape);return{x:()=>Hp(e,s)}}},{kernelName:Cr,gradFunc:e=>({x:()=>qo(e)})},{kernelName:$r,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Xu(Vo(e,Go(pu(n,1.5),2)))}}},{kernelName:Or,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>Lo(qo(n),"float32"),t:()=>Go(e,Lo(n,e.dtype)),e:()=>Go(e,Lo(Zh(n),e.dtype))}}},ky,{kernelName:zr,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Go(e,Go(n,du(tu(1),n)))}}},{kernelName:Lr,gradFunc:e=>({x:()=>qo(e)})},{kernelName:Dr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Go(Jc(Lo(n,"float32")),e)}}},{kernelName:Mr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Go(Zc(Lo(n,"float32")),e)}}},{kernelName:_r,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{begin:s,size:a}=n,i=r.shape,[o,u]=El(r,s,a),l=[];for(let t=0;t<e.rank;t++)l.push([o[t],i[t]-o[t]-u[t]]);return{x:()=>wp(e,l)}}},{kernelName:Gr,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{dim:s}=n,a=Go(e,r);return{logits:()=>du(a,Go(Nh(a,[s],!0),r))}}},{kernelName:Pr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Go(e,Sc(n))}}},Iy,Iy,Ny,Ny,{kernelName:Br,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Vo(e,Go(jo(Lo(n,"float32")),2))}}},{kernelName:Yr,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=tu(2);return{a:()=>Go(e,Go(s,du(n,r))),b:()=>Go(e,Go(s,du(r,n)))}}},{kernelName:Jr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Go(e,Go(Lo(n,"float32"),2))}}},{kernelName:ms,gradFunc:e=>({x:()=>qo(e)})},{kernelName:rs,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,s=bu(n.shape,r.shape);return{a:()=>{let t=e;const r=yu(n.shape,s);return r.length>0&&(t=Nh(t,r)),vc(t,n.shape)},b:()=>{let t=e;const n=yu(r.shape,s);return n.length>0&&(t=Nh(t,n)),vc(Xu(t),r.shape)}}}},{kernelName:Wr,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,s=r.shape.slice(),{axis:a}=n;we(a,r.shape).forEach((e=>{s[e]=1}));const i=vc(e,s),o=Go(i,lp(r.shape,"float32"));return{x:()=>o}}},{kernelName:ss,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Vo(e,Ho(Jc(n)))}}},{kernelName:as,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Go(du(tu(1),Ho(n)),e)}}},{kernelName:is,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{reps:s}=n;return{x:()=>{let t=qo(r);if(1===r.rank)for(let n=0;n<s[0];++n)t=Wo(t,Tc(e,[n*r.shape[0]],[r.shape[0]]));else if(2===r.rank)for(let n=0;n<s[0];++n)for(let a=0;a<s[1];++a)t=Wo(t,Tc(e,[n*r.shape[0],a*r.shape[1]],[r.shape[0],r.shape[1]]));else if(3===r.rank)for(let n=0;n<s[0];++n)for(let a=0;a<s[1];++a)for(let i=0;i<s[2];++i)t=Wo(t,Tc(e,[n*r.shape[0],a*r.shape[1],i*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(4!==r.rank)throw new Error(`Gradient for tile operation is not implemented for rank-${r.rank} tensors yet.`);for(let n=0;n<s[0];++n)for(let a=0;a<s[1];++a)for(let i=0;i<s[2];++i)for(let o=0;o<s[3];++o)t=Wo(t,Tc(e,[n*r.shape[0],a*r.shape[1],i*r.shape[2],o*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return t}}}},{kernelName:ls,gradFunc:(e,t,n)=>{const r=n,{perm:s}=r,a=wh(s);return{x:()=>Ju(e,a)}}},{kernelName:hs,gradFunc:(e,t,n)=>{const r=n,{axis:s}=r;return{value:()=>yd(e,s)}}},{kernelName:ps,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>function(e,t){const n=xu(t,qo(t)),r=_h(e,n);let s=Mh(t,tu(0,"int32"));const a=r.rank-s.rank;for(let e=0;e<a;++e)s=Eh(s,e+1);s=Jh(s,lp(r.shape,"bool"));const i=qo(r);return oh(s,r,i)}(e,n)}}},{kernelName:fs,gradFunc:e=>({x:()=>qo(e)})}];for(const e of Sy)As(e);va().prototype.abs=function(){return this.throwIfDisposed(),mu(this)},va().prototype.acos=function(){return this.throwIfDisposed(),Kl(this)},va().prototype.acosh=function(){return this.throwIfDisposed(),Xl(this)},va().prototype.add=function(e){return this.throwIfDisposed(),Wo(this,e)},va().prototype.all=function(e,t){return this.throwIfDisposed(),Jl(this,e,t)},va().prototype.any=function(e,t){return this.throwIfDisposed(),Zl(this,e,t)},va().prototype.argMax=function(e){return this.throwIfDisposed(),Ql(this,e)},va().prototype.argMin=function(e){return this.throwIfDisposed(),ec(this,e)},va().prototype.asScalar=function(){return this.throwIfDisposed(),ie(1===this.size,(()=>"The array must have only 1 element.")),vc(this,[])},va().prototype.asType=function(e){return this.throwIfDisposed(),Lo(this,e)},va().prototype.as1D=function(){return this.throwIfDisposed(),vc(this,[this.size])},va().prototype.as2D=function(e,t){return this.throwIfDisposed(),vc(this,[e,t])},va().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),vc(this,[e,t,n])},va().prototype.as4D=function(e,t,n,r){return this.throwIfDisposed(),vc(this,[e,t,n,r])},va().prototype.as5D=function(e,t,n,r,s){return this.throwIfDisposed(),vc(this,[e,t,n,r,s])},va().prototype.asin=function(){return this.throwIfDisposed(),tc(this)},va().prototype.asinh=function(){return this.throwIfDisposed(),nc(this)},va().prototype.atan=function(){return this.throwIfDisposed(),rc(this)},va().prototype.atan2=function(e){return this.throwIfDisposed(),sc(this,e)},va().prototype.atanh=function(){return this.throwIfDisposed(),ac(this)},va().prototype.avgPool=function(e,t,n,r){return this.throwIfDisposed(),kc(this,e,t,n,r)},va().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),Ec(this,e,t)},va().prototype.batchNorm=function(e,t,n,r,s){return this.throwIfDisposed(),Ac(this,e,t,n,r,s)},va().prototype.broadcastTo=function(e){return this.throwIfDisposed(),Lc(this,e)},va().prototype.cast=function(e){return this.throwIfDisposed(),Lo(this,e)},va().prototype.ceil=function(){return this.throwIfDisposed(),zc(this)},va().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),Pc(this,e,t)},va().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof wa&&(e=[e]),Nc([this,...e],t)},va().prototype.conv1d=function(e,t,n,r,s,a){return this.throwIfDisposed(),jc(this,e,t,n,r,s,a)},va().prototype.conv2dTranspose=function(e,t,n,r,s){return this.throwIfDisposed(),qc(this,e,t,n,r,s)},va().prototype.conv2d=function(e,t,n,r,s,a){return this.throwIfDisposed(),Gc(this,e,t,n,r,s,a)},va().prototype.cos=function(){return this.throwIfDisposed(),Jc(this)},va().prototype.cosh=function(){return this.throwIfDisposed(),Zc(this)},va().prototype.cumprod=function(e,t,n){return this.throwIfDisposed(),Qc(this,e,t,n)},va().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),eh(this,e,t,n)},va().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),nh(this,e,t)},va().prototype.depthwiseConv2d=function(e,t,n,r,s,a){return this.throwIfDisposed(),rh(this,e,t,n,r,s,a)},va().prototype.dilation2d=function(e,t,n,r,s){return this.throwIfDisposed(),ah(this,e,t,n,r,s)},va().prototype.divNoNan=function(e){return this.throwIfDisposed(),uh(this,e)},va().prototype.div=function(e){return this.throwIfDisposed(),Vo(this,e)},va().prototype.dot=function(e){return this.throwIfDisposed(),lh(this,e)},va().prototype.elu=function(){return this.throwIfDisposed(),hh(this)},va().prototype.equal=function(e){return this.throwIfDisposed(),ih(this,e)},va().prototype.erf=function(){return this.throwIfDisposed(),dh(this)},va().prototype.euclideanNorm=function(e,t){return this.throwIfDisposed(),Ch(this,e,t)},va().prototype.exp=function(){return this.throwIfDisposed(),$h(this)},va().prototype.expandDims=function(e){return this.throwIfDisposed(),Eh(this,e)},va().prototype.expm1=function(){return this.throwIfDisposed(),Ah(this)},va().prototype.fft=function(){return this.throwIfDisposed(),cd(this)},va().prototype.flatten=function(){return this.throwIfDisposed(),vc(this,[this.size])},va().prototype.floor=function(){return this.throwIfDisposed(),Fh(this)},va().prototype.floorDiv=function(e){return this.throwIfDisposed(),Uo(this,e)},va().prototype.gather=function(e,t,n){return this.throwIfDisposed(),_h(this,e,t,n)},va().prototype.greaterEqual=function(e){return this.throwIfDisposed(),Mh(this,e)},va().prototype.greater=function(e){return this.throwIfDisposed(),Dh(this,e)},va().prototype.ifft=function(){return this.throwIfDisposed(),hd(this)},va().prototype.irfft=function(){return this.throwIfDisposed(),pd(this)},va().prototype.isFinite=function(){return this.throwIfDisposed(),Lh(this)},va().prototype.isInf=function(){return this.throwIfDisposed(),zh(this)},va().prototype.isNaN=function(){return this.throwIfDisposed(),Ph(this)},va().prototype.leakyRelu=function(e){return this.throwIfDisposed(),Bh(this,e)},va().prototype.lessEqual=function(e){return this.throwIfDisposed(),Uh(this,e)},va().prototype.less=function(e){return this.throwIfDisposed(),Wh(this,e)},va().prototype.localResponseNormalization=function(e,t,n,r){return this.throwIfDisposed(),Gh(this,e,t,n,r)},va().prototype.logSigmoid=function(){return this.throwIfDisposed(),Kh(this)},va().prototype.logSoftmax=function(e){return this.throwIfDisposed(),Xh(this,e)},va().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),Yh(this,e,t)},va().prototype.log=function(){return this.throwIfDisposed(),jh(this)},va().prototype.log1p=function(){return this.throwIfDisposed(),Hh(this)},va().prototype.logicalAnd=function(e){return this.throwIfDisposed(),Jh(this,e)},va().prototype.logicalNot=function(){return this.throwIfDisposed(),Zh(this)},va().prototype.logicalOr=function(e){return this.throwIfDisposed(),Qh(this,e)},va().prototype.logicalXor=function(e){return this.throwIfDisposed(),ep(this,e)},va().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),Hu(this,e,t,n)},va().prototype.maxPool=function(e,t,n,r){return this.throwIfDisposed(),sp(this,e,t,n,r)},va().prototype.max=function(e,t){return this.throwIfDisposed(),kh(this,e,t)},va().prototype.maximum=function(e){return this.throwIfDisposed(),xu(this,e)},va().prototype.mean=function(e,t){return this.throwIfDisposed(),op(this,e,t)},va().prototype.min=function(e,t){return this.throwIfDisposed(),Ih(this,e,t)},va().prototype.minimum=function(e){return this.throwIfDisposed(),hp(this,e)},va().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),pp(this,e,t)},va().prototype.mod=function(e){return this.throwIfDisposed(),dp(this,e)},va().prototype.mul=function(e){return this.throwIfDisposed(),Go(this,e)},va().prototype.neg=function(){return this.throwIfDisposed(),Xu(this)},va().prototype.norm=function(e,t,n){return this.throwIfDisposed(),Th(this,e,t,n)},va().prototype.notEqual=function(e){return this.throwIfDisposed(),yp(this,e)},va().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),qu(this,e,t,n)},va().prototype.onesLike=function(){return this.throwIfDisposed(),bp(this)},va().prototype.pad=function(e,t){return this.throwIfDisposed(),wp(this,e,t)},va().prototype.pool=function(e,t,n,r,s,a){return this.throwIfDisposed(),Tp(this,e,t,n,r,s,a)},va().prototype.pow=function(e){return this.throwIfDisposed(),pu(this,e)},va().prototype.prelu=function(e){return this.throwIfDisposed(),Cp(this,e)},va().prototype.prod=function(e,t){return this.throwIfDisposed(),$p(this,e,t)},va().prototype.reciprocal=function(){return this.throwIfDisposed(),Vp(this)},va().prototype.relu=function(){return this.throwIfDisposed(),Gp(this)},va().prototype.relu6=function(){return this.throwIfDisposed(),jp(this)},va().prototype.reshapeAs=function(e){return this.throwIfDisposed(),vc(this,e.shape)},va().prototype.reshape=function(e){return this.throwIfDisposed(),vc(this,e)},va().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),Nf(this,e,t,n)},va().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),Sf(this,e,t,n)},va().prototype.reverse=function(e){return this.throwIfDisposed(),Hp(this,e)},va().prototype.rfft=function(){return this.throwIfDisposed(),fd(this)},va().prototype.round=function(){return this.throwIfDisposed(),Jp(this)},va().prototype.rsqrt=function(){return this.throwIfDisposed(),Zp(this)},va().prototype.selu=function(){return this.throwIfDisposed(),Qp(this)},va().prototype.separableConv2d=function(e,t,n,r,s,a){return this.throwIfDisposed(),ed(this,e,t,n,r,s,a)},va().prototype.sigmoid=function(){return this.throwIfDisposed(),Sc(this)},va().prototype.sign=function(){return this.throwIfDisposed(),nd(this)},va().prototype.sin=function(){return this.throwIfDisposed(),rd(this)},va().prototype.sinh=function(){return this.throwIfDisposed(),sd(this)},va().prototype.slice=function(e,t){return this.throwIfDisposed(),Tc(this,e,t)},va().prototype.softmax=function(e){return this.throwIfDisposed(),ld(this,e)},va().prototype.softplus=function(){return this.throwIfDisposed(),qh(this)},va().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),Sp(this,e,t)},va().prototype.split=function(e,t){return this.throwIfDisposed(),dd(this,e,t)},va().prototype.sqrt=function(){return this.throwIfDisposed(),jo(this)},va().prototype.square=function(){return this.throwIfDisposed(),Ho(this)},va().prototype.squaredDifference=function(e){return this.throwIfDisposed(),md(this,e)},va().prototype.squeeze=function(e){return this.throwIfDisposed(),gd(this,e)},va().prototype.stack=function(e,t){this.throwIfDisposed();const n=e instanceof wa?[this,e]:[this,...e];return yd(n,t)},va().prototype.step=function(e){return this.throwIfDisposed(),bd(this,e)},va().prototype.stridedSlice=function(e,t,n,r,s,a,i,o){return this.throwIfDisposed(),xd(this,e,t,n,r,s,a,i,o)},va().prototype.sub=function(e){return this.throwIfDisposed(),du(this,e)},va().prototype.sum=function(e,t){return this.throwIfDisposed(),Nh(this,e,t)},va().prototype.tan=function(){return this.throwIfDisposed(),wd(this)},va().prototype.tanh=function(){return this.throwIfDisposed(),Cc(this)},va().prototype.tile=function(e){return this.throwIfDisposed(),Rh(this,e)},va().prototype.toBool=function(){return this.throwIfDisposed(),Lo(this,"bool")},va().prototype.toFloat=function(){return this.throwIfDisposed(),Lo(this,"float32")},va().prototype.toInt=function(){return this.throwIfDisposed(),Lo(this,"int32")},va().prototype.topk=function(e,t){return this.throwIfDisposed(),Cd(this,e,t)},va().prototype.transpose=function(e){return this.throwIfDisposed(),Ju(this,e)},va().prototype.unique=function(e){return this.throwIfDisposed(),Ed(this,e)},va().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),Ad(this,e,t)},va().prototype.unstack=function(e){return this.throwIfDisposed(),Rd(this,e)},va().prototype.where=function(e,t){return this.throwIfDisposed(),oh(e,this,t)},va().prototype.zerosLike=function(){return this.throwIfDisposed(),qo(this)};class Ty extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ty.prototype)}}class Cy extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Cy.prototype)}}class $y extends Error{constructor(e){super(e),Object.setPrototypeOf(this,$y.prototype)}}class Ey extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ey.prototype)}}class Ay extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ay.prototype)}}Error;class Ry{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){const e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;t<this.maxEntries-e;t++){const e=this.cache.keys().next().value;this.cache.delete(e)}this.maxEntries=e}}function Oy(e,t){if(Array.isArray(e)){let n=[];for(let r=0;r<t;r++)n=n.concat(e);return n}{const n=new Array(t);return n.fill(e),n}}function Fy(e,t){if(!e)throw new Ay(t)}function _y(e,t){let n=0;for(const r of e)r===t&&n++;return n}function Dy(e){return 1===e.length?e[0]:e}function My(e){return Array.isArray(e)?e:[e]}function Ly(e){const t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return"_"!==t[0]?t:"private"+t}function zy(e){return e.length<=1||-1===e.indexOf("_")?e:e.replace(/[_]+(\w|$)/g,((e,t)=>t.toUpperCase()))}let Py={};function By(e){if(null==e)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function Wy(e){if(null!=e&&"object"==typeof e)if(Array.isArray(e))e.forEach((e=>Wy(e)));else{const t=Object.keys(e);for(const n of t){const t=e[n];null!=t&&"object"==typeof t&&(Array.isArray(t)||"ndarray"!==t.type||"number"!=typeof t.value?Wy(t):e[n]=t.value)}}}function Uy(e,t={},n={},r="object",s=!1){if("string"==typeof e){const s=e;let a;if(s in n)a=n[s];else if(s in Py)a=Py[s];else if(a=t[s],null==a)throw new $y(`Unknown ${r}: ${e}. This may be due to one of the following reasons:\n1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return a}{const a=e;if(null==a.className||null==a.config)throw new $y(`${r}: Improper config format: ${JSON.stringify(a)}.\n'className' and 'config' must set.`);const i=a.className;let o,u;if(i in n?[o,u]=n[i]:i in Py?[o,u]=Py.className:i in t&&([o,u]=t[i]),null==o)throw new $y(`Unknown ${r}: ${i}. This may be due to one of the following reasons:\n1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(null!=u){const e={};for(const t of Object.keys(Py))e[t]=Py[t];for(const t of Object.keys(n))e[t]=n[t];a.config.customObjects=e;const t=Object.assign({},Py);for(const e of Object.keys(n))Py[e]=n[e];Wy(a.config);const r=u(o,a.config,n,s);return Py=Object.assign({},t),r}{const e=Object.assign({},Py);for(const e of Object.keys(n))Py[e]=n[e];const t=new o(a.config);return Py=Object.assign({},e),t}}}function Vy(e,t){return-1*function(e,t){return e<t?-1:e>t?1:0}(e,t)}function Gy(e){if(null==e)return e;const t=[];for(const n of e)-1===t.indexOf(n)&&t.push(n);return t}function jy(e){if(null==e)throw new $y(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function Hy(e,t,n){if(null!=n&&e.indexOf(n)<0)throw new $y(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function qy(e,t,n=0,r=1/0){return Fy(n>=0),Fy(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every((e=>typeof e===t))}function Ky(e,t){Array.isArray(e)?(ie(e.length>0,(()=>`${t} is unexpectedly an empty array.`)),e.forEach(((e,n)=>Ky(e,`element ${n+1} of ${t}`)))):ie(Number.isInteger(e)&&e>0,(()=>`Expected ${t} to be a positive integer, but got ${Xy(e)}.`))}function Xy(e){return null===e?"null":Array.isArray(e)?"["+e.map((e=>Xy(e))).join(",")+"]":"string"==typeof e?`"${e}"`:`${e}`}function Yy(e){return"relu"===e?"relu":"linear"===e?"linear":"elu"===e?"elu":null}let Jy=0;function Zy(){return Jy++}const Qy={};function eb(e=""){return e in Qy||(Qy[e]=0),Qy[e]+=1,e+Qy[e].toString()}const tb=["channelsFirst","channelsLast"],nb=["nearest","bilinear"],rb=["valid","same","causal"],sb=["max","avg"],ab=["sum","mul","concat","ave"],ib=new Map;function ob(e){Hy(tb,"DataFormat",e)}function ub(e){Hy(rb,"PaddingMode",e)}function lb(e){Hy(sb,"PoolMode",e)}const cb=[];function hb(e,t){cb.push(e);try{const e=t();return cb.pop(),e}catch(e){throw cb.pop(),e}}function pb(e){if(!mb(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===cb.length?"":cb.join("/")+"/")+e}function db(e){if(!mb(e))throw new Error("Not a valid tensor name: '"+e+"'");ib.has(e)||ib.set(e,0);const t=ib.get(e);if(ib.set(e,ib.get(e)+1),t>0){const n=`${e}_${t}`;return ib.set(n,1),n}return e}const fb=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function mb(e){return!!e.match(fb)}function gb(e,t,n){null==t&&(t=0),null==n&&(n=e.length);let r=1;for(let s=t;s<n;++s)r*=e[s];return r}function yb(e){if(0===e.length)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let n=0;n<e.length;n++){const r=e[n];r<t&&(t=r)}return t}function bb(e){if(0===e.length)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){const r=e[n];r>t&&(t=r)}return t}function xb(e,t){if(t<e)throw new $y(`end (${t}) < begin (${e}) is forbidden.`);const n=[];for(let r=e;r<t;++r)n.push(r);return n}let wb;function vb(){return null==wb&&(wb=Ri().epsilon()),wb}function kb(e,t){return Lo(e,t)}function Ib(e,t=-1){const n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),vc(e,n)}function Nb(e,t,n){return wi((()=>{switch(e.rank){case 1:return ad(e,t,n);case 2:return id(e,[t,0],[n,e.shape[1]]);case 3:return od(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return ud(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Tc(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Tc(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new $y(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Sb(e,t,n){return wi((()=>{switch(e.rank){case 1:return ad(e,t,n);case 2:return id(e,[0,t],[e.shape[0],n]);case 3:return od(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return ud(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new $y(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Tb(e,t,n,r){return wi((()=>{switch(e.rank){case 1:return ad(e,t,n);case 2:switch(r){case 1:return Nb(e,t,n);case 2:return Sb(e,t,n);default:throw new $y(`The axis is not within the rank of the tensor ${r}`)}case 3:switch(r){case 1:return Nb(e,t,n);case 2:return od(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Sb(e,t,n);default:throw new $y(`The axis is not within the rank of the tensor ${r}`)}case 4:switch(r){case 1:return Nb(e,t,n);case 2:return ud(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return ud(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Sb(e,t,n);default:throw new $y(`The axis is not within the rank of the tensor ${r}`)}default:throw new $y(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Cb(e,t=-1){let n;return t<0&&(n=e[0].rank,t=0!==n?n:0),t===e[0].rank&&(t=-1),Nc(e,t)}function $b(e,t){switch(e.rank){case 1:return Bc([e,t]);case 2:return Wc([e,t],0);case 3:return Uc([e,t],0);case 4:return Vc([e,t],0);default:throw new $y(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Eb(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new $y(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Rh(e,t)}function Ab(e,t=0,n=1,r,s){return zp(e,t,n,r,s)}function Rb(e,t,n,r){if(e.rank<2||t.rank<2)throw new Ey(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3&&e.shape.slice(-1)[0]!==t.shape.slice(-2)[0])throw new Ey(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`);if(2===e.rank&&2===t.rank)return ef({a:e,b:t,transposeA:!1,transposeB:!1,bias:r?_b(e.rank,r,"channelsLast"):null,activation:n});{const s=e.shape.slice(),a=s.pop();e=vc(e,[-1,a]);const i=t.shape.slice(),o=i.pop(),u=i.pop(),l=[...i,o],c=Array.from({length:t.rank},((e,n)=>0===n?t.rank-2:n<=t.rank-2?n-1:n));t=vc(Ju(t,c),[u,-1]);const h=[...s,...l];return vc(ef({a:e,b:t,transposeA:!1,transposeB:!1,bias:r?_b(e.rank,r,"channelsLast"):null,activation:n}),h)}}function Ob(e,t,n){return wi((()=>(t=Array.isArray(t)?vd(t,"int32"):Lo(t,"int32"),_h(e,t,n))))}function Fb(e){return Go(e,e)}function _b(e,t,n){const r=t.shape;if(1!==t.rank&&t.rank!==e)throw new $y(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(5===e){if("channelsFirst"===n)return 1===r.length?vc(t,[1,r[0],1,1,1]):vc(t,[1,r[3],r[0],r[1],r[2]]);if("channelsLast"===n)return 1===r.length?vc(t,[1,1,1,1,r[0]]):vc(t,[1].concat(r))}else if(4===e){if("channelsFirst"===n)return 1===r.length?vc(t,[1,r[0],1,1]):vc(t,[1,r[2],r[0],r[1]]);if("channelsLast"===n)return 1===r.length?vc(t,[1,1,1,r[0]]):vc(t,[1].concat(r))}else if(3===e){if("channelsFirst"===n)return 1===r.length?vc(t,[1,r[0],1]):vc(t,[1,r[1],r[0]]);if("channelsLast"===n)return 1===r.length?vc(t,[1,1,r[0]]):vc(t,[1].concat(r))}else if(e<3)return t;throw new $y(`Unsupported input rank by biasAdd: ${t.rank}`)}function Db(e,t,n){return wi((()=>(null==n&&(n="channelsLast"),ob(n),Wo(e,_b(e.rank,t,n)))))}function Mb(e,t,n,r){return wi((()=>Wd(e,t,n,r)))}function Lb(e,t,n=!1){return n?e():t()}const zb=["fanIn","fanOut","fanAvg"],Pb=["normal","uniform","truncatedNormal"];var Bb=n(96763);class Wb extends su{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class Ub extends Wb{apply(e,t){return up(e,t)}}Ub.className="Zeros",iu(Ub);class Vb extends Wb{apply(e,t){return lp(e,t)}}Vb.className="Ones",iu(Vb);class Gb extends Wb{constructor(e){if(super(),"object"!=typeof e)throw new $y(`Expected argument of type ConstantConfig but got ${e}`);if(void 0===e.value)throw new $y(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return wi((()=>Go(tu(this.value),lp(e,t))))}getConfig(){return{value:this.value}}}Gb.className="Constant",iu(Gb);class jb extends Wb{constructor(e){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return Bp(e,this.minval,this.maxval,t,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}jb.className="RandomUniform",iu(jb);class Hb extends Wb{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Ey(`randomNormal does not support dType ${t}.`);return Ab(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Hb.className="RandomNormal",iu(Hb);class qb extends Wb{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Ey(`truncatedNormal does not support dType ${t}.`);return $d(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}qb.className="TruncatedNormal",iu(qb);class Kb extends Wb{constructor(e){super(),this.gain=null!=e.gain?e.gain:1}apply(e,t){return wi((()=>{if(2!==e.length||e[0]!==e[1])throw new $y("Identity matrix initializer can only be used for 2D square matrices.");return Go(this.gain,Oh(e[0]))}))}getConfig(){return{gain:this.gain}}}Kb.className="Identity",iu(Kb);class Xb extends Wb{constructor(e){if(super(),e.scale<0)throw new $y(`scale must be a positive float. Got: ${e.scale}`);var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t=this.mode,Hy(zb,"FanMode",t),this.distribution=null==e.distribution?"normal":e.distribution,function(e){Hy(Pb,"Distribution",e)}(this.distribution),this.seed=e.seed}apply(e,t){const n=function(e,t="channelsLast"){let n,r;if(ob(t),2===e.length)n=e[0],r=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){const t=gb(e,2);n=e[1]*t,r=e[0]*t}else if("channelsLast"===t){const t=gb(e,0,e.length-2);n=e[e.length-2]*t,r=e[e.length-1]*t}}else{const t=gb(e);n=Math.sqrt(t),r=Math.sqrt(t)}return[n,r]}(e),r=n[0],s=n[1];let a=this.scale;if("fanIn"===this.mode?a/=Math.max(1,r):"fanOut"===this.mode?a/=Math.max(1,s):a/=Math.max(1,(r+s)/2),"normal"===this.distribution){const n=Math.sqrt(a);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Ey(`${this.getClassName()} does not support dType ${t}.`);return $d(e,0,n,t,this.seed)}{const n=Math.sqrt(3*a);return Bp(e,-n,n,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}Xb.className="VarianceScaling",iu(Xb);class Yb extends Xb{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Xb.className}}Yb.className="GlorotUniform",iu(Yb);class Jb extends Xb{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Xb.className}}Jb.className="GlorotNormal",iu(Jb);class Zb extends Xb{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Xb.className}}Zb.className="HeNormal",iu(Zb);class Qb extends Xb{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Xb.className}}Qb.className="HeUniform",iu(Qb);class ex extends Xb{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Xb.className}}ex.className="LeCunNormal",iu(ex);class tx extends Xb{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Xb.className}}tx.className="LeCunUniform",iu(tx);class nx extends Wb{constructor(e){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=null==e.gain?this.DEFAULT_GAIN:e.gain,this.seed=e.seed}apply(e,t){return wi((()=>{if(e.length<2)throw new Ey("Shape must be at least 2D.");if("int32"!==t&&"float32"!==t&&void 0!==t)throw new TypeError(`Unsupported data type ${t}.`);const n=le(e.slice(0,-1)),r=e[e.length-1],s=n*r;s>this.ELEMENTS_WARN_SLOW&&Bb.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${s}) elements: Slowness may result.`);const a=Ab([Math.max(r,n),Math.min(r,n)],0,1,t,this.seed),i=Qf.qr(a,!1);let o=i[0];const u=i[1].flatten().stridedSlice([0],[Math.min(r,n)*Math.min(r,n)],[Math.min(r,n)+1]);return o=Go(o,u.sign()),n<r&&(o=o.transpose()),Go(tu(this.gain),o.reshape(e))}))}getConfig(){return{gain:this.gain,seed:this.seed}}}nx.className="Orthogonal",iu(nx);const rx={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function sx(e,t={}){return Uy(e,au.getMap().classNameMap,t,"initializer")}function ax(e){return By(e)}function ix(e){if("string"==typeof e){const t=e in rx?rx[e]:e;if("GlorotNormal"===t)return new Jb;if("GlorotUniform"===t)return new Yb;if("HeNormal"===t)return new Zb;if("HeUniform"===t)return new Qb;if("LeCunNormal"===t)return new ex;if("LeCunUniform"===t)return new tx;{const e={};return e.className=t,e.config={},sx(e)}}return e instanceof Wb?e:sx(e)}function ox(e){return Array.isArray(e)&&Array.isArray(e[0])}function ux(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e]}function lx(e){let t;if(Array.isArray(e)){if(1!==e.length)throw new $y(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function cx(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return e[0];throw new $y(`Expected exactly 1 Shape; got ${e.length}`)}return e}function hx(e){let t=0;for(const n of e)0===n.shape.length?t+=1:t+=n.shape.reduce(((e,t)=>e*t));return t}const px="Variable";class dx{constructor(e,t="float32",n=px,r=!0,s=null){this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=Zy(),n=null==n?px:n,this.originalName=pb(n),this.name=db(this.originalName),this.trainable_=r,this.constraint=s,this.val=Fd(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),function(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}(this.val,e),this.val.id!==e.id&&(this.val.assign(e),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}}function fx(e){return e.map((e=>e.read()))}function mx(e){e.forEach((e=>{e[0].write(e[1])}))}var gx=n(96763);class yx{constructor(e){this.dtype=e.dtype,this.shape=e.shape,null!=e.shape?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class bx{constructor(e,t,n,r,s,a,i){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=r,this.callArgs=s,this.outputTensorIndex=i,this.id=Zy(),null!=a&&(this.originalName=pb(a),this.name=db(this.originalName)),this.rank=t.length}}let xx=0;class wx{constructor(e,t){this.callArgs=t,this.id=xx++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const t of e.inboundLayers)null!=t&&t.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)null!=t?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let vx=0;class kx extends su{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=vx++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const e=this.getClassName();t=Ly(e)+"_"+eb(e)}if(this.name=t,this.trainable_=null==e.trainable||e.trainable,null!=e.inputShape||null!=e.batchInputShape){let t;if(null!=e.batchInputShape)t=e.batchInputShape;else if(null!=e.inputShape){let n=null;null!=e.batchSize&&(n=e.batchSize),t=[n].concat(e.inputShape)}this.batchInputShape=t;let n=e.dtype;null==n&&(n=e.inputDType),null==n&&(n="float32"),this.dtype=n}null!=e.weights?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(0===this.inboundNodes.length)throw new Cy(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new $y(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Dy(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Dy(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Ty(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(0===this.inboundNodes.length)throw new Ty(`Layer ${this.name} is not connected, no input to return.`);return Dy(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new Ty(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Ty(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Dy(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map((e=>e()))}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach((t=>t.trainable=e)),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter((e=>e.trainable)):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter((e=>!e.trainable)).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){const t=My(e);if(null==this.inputSpec||0===this.inputSpec.length)return;const n=My(this.inputSpec);if(t.length!==n.length)throw new $y(`Layer ${this.name} expects ${n.length} inputs, but it received ${t.length} input tensors. Input received: ${e}`);for(let e=0;e<t.length;e++){const r=t[e],s=n[e];if(null==s)continue;const a=r.rank;if(null!=s.ndim&&a!==s.ndim)throw new $y(`Input ${e} is incompatible with layer ${this.name}: expected ndim=${s.ndim}, found ndim=${a}`);if(null!=s.maxNDim&&a>s.maxNDim)throw new $y(`Input ${e} is incompatible with layer ${this.name}: expected max_ndim=${s.maxNDim}, found ndim=${a}`);if(null!=s.minNDim&&a<s.minNDim)throw new $y(`Input ${e} is incompatible with layer ${this.name}: expected min_ndim=${s.minNDim}, found ndim=${a}.`);if(null!=s.dtype&&r.dtype!==s.dtype)throw new $y(`Input ${e} is incompatible with layer ${this.name} : expected dtype=${s.dtype}, found dtype=${r.dtype}.`);if(s.axes){const t=r.shape;for(const n in s.axes){const r=Number(n),a=s.axes[n],i=r>=0?t[r]:t[t.length+r];if(null!=a&&-1===[a,null].indexOf(i))throw new $y(`Input ${e} is incompatible with layer ${this.name}: expected axis ${r} of input shape to have value ${a} but got shape ${t}.`)}}if(null!=s.shape)for(let t=0;t<s.shape.length;++t){const n=s.shape[t],a=r.shape[t];if(null!=n&&null!=a&&n!==a)throw new $y(`Input ${e} is incompatible with layer ${this.name}: expected shape=${s.shape}, found shape=${r.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){null!=this._callHook&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();const n=My(e),r=function(e){let t=!0;for(const n of My(e))if(!(n instanceof bx)){t=!1;break}return t}(e),s=function(e){let t=!0;for(const n of My(e))if(n instanceof bx){t=!1;break}return t}(e);if(r===s)throw new $y("Arguments to apply() must be all SymbolicTensors or all Tensors");return hb(this.name,(()=>{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of My(e))t.push(n.shape);this.build(Dy(t)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),null===this._refCount&&s&&(this._refCount=1)}if(this.assertInputCompatibility(e),s){let r=this.call(e,t);this.supportsMasking&&this.setMaskMetadata(e,r);const s=My(r),a=[];for(let e of s)-1!==n.indexOf(e)&&(e=e.clone()),a.push(e);if(r=Dy(a),null!=this.activityRegularizer)throw new Ey("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return r}{const n=function(e){e=My(e);const t=[];for(const n of e)t.push(n.shape);return Dy(t)}(e),r=this.computeOutputShape(n);let s;const a="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(e)?n[0]:n),s=null!=r&&r.length>0&&Array.isArray(r[0])?r.map(((n,r)=>new bx(a,n,this,My(e),t,this.name,r))):new bx(a,r,this,My(e),t,this.name),this.addInboundNode(e,s,null,null,n,r,t),this._refCount++,null!=this.activityRegularizer)throw new Ey("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}}))}warnOnIncompatibleInputShape(e){if(null!=this.batchInputShape)if(e.length!==this.batchInputShape.length)gx.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach(((n,r)=>{null!=n&&null!=e[r]&&e[r]!==n&&(t=!0)})),t&&gx.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new Ty(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const n=JSON.stringify(t.outputShapes);-1===e.indexOf(n)&&e.push(n)}if(1===e.length){const e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&1===e.length?e[0]:e}throw new Ty(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new Cy(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return hx(this.weights)}build(e){this.built=!0}getWeights(e=!1){return fx(e?this.trainableWeights:this.weights)}setWeights(e){wi((()=>{const t=this.weights;if(t.length!==e.length)throw new $y(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(0===t.length)return;const n=[],r=fx(t);for(let s=0;s<r.length;++s){const a=r[s],i=t[s],o=e[s];if(!pe(a.shape,o.shape))throw new $y(`Layer weight shape ${a.shape} not compatible with provided weight shape ${o.shape}`);n.push([i,o])}mx(n)}))}addWeight(e,t,n,r,s,a,i,o){if(-1!==this._addedWeightNames.indexOf(e))throw new $y(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(r=null!=o?o():ix("zeros"));const u=r.apply(t,n),l=new dx(u,n,e,a,i);return u.dispose(),null!=s&&this.addLoss((()=>s.apply(l.read()))),null==a&&(a=!0),a?this._trainableWeights.push(l):this._nonTrainableWeights.push(l),l}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){null==e||Array.isArray(e)&&0===e.length||(e=My(e),void 0!==this._losses&&null!==this._losses&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(null!=t){if(!Array.isArray(t))throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);t.forEach((e=>{if(null!=e)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)}))}return null}return t}setMaskMetadata(e,t,n){if(!this.supportsMasking)return;const r=this.computeMask(e,n),s=My(t),a=My(r);if(s.length!==a.length)throw new Error(`${this.name} outputs ${s.length} tensors but ${s.length} masks for those tensors`);for(let e=0;e<s.length;e++)s[e].kerasMask=a[e]}addInboundNode(e,t,n,r,s,a,i=null){const o=My(e);t=My(t),n=My(n),r=My(r),s=ux(s),a=ux(a);const u=[],l=[],c=[];for(const e of o)u.push(e.sourceLayer),l.push(e.nodeIndex),c.push(e.tensorIndex);new wx({outboundLayer:this,inboundLayers:u,nodeIndices:l,tensorIndices:c,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:r,inputShapes:s,outputShapes:a},i);for(let e=0;e<t.length;e++)t[e].sourceLayer=this,t[e].nodeIndex=this.inboundNodes.length-1,t[e].tensorIndex=e}getConfig(){const e={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(e.batchInputShape=this.batchInputShape),null!=this.dtype&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach((e=>e.dispose())),this.weights.length}assertNotDisposed(){if(0===this._refCount)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(null===this._refCount)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return 0==--this._refCount&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function Ix(e,t,n){if((null==t||null!=n&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),0===t.inboundNodes.length)return[e];{const e=t.inboundNodes[n];if(0===e.inboundLayers.length)return e.inputTensors;{const t=[];for(let n=0;n<e.inboundLayers.length;n++){const r=Ix(e.inputTensors[n],e.inboundLayers[n],e.nodeIndices[n]);for(const e of r)-1===t.indexOf(e)&&t.push(e)}return t}}}class Nx extends kx{constructor(e){if(super({dtype:e.dtype,name:null!=e.name?e.name:eb("input").toString()}),null==e.batchSize&&(e.batchSize=null),null==e.sparse&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,null!=e.inputShape&&null!=e.batchInputShape)throw new $y("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(null==t){if(null==e.inputShape)throw new $y("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new $y("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];const r=new bx(this.dtype,this.batchInputShape,this,[],{},this.name);r.nodeIndex=0,r.tensorIndex=0,new wx({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[r],outputTensors:[r],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new $y(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}}function Sx(e){if(null==e.batchShape&&null==e.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=e.batchShape&&null!=e.shape)throw new $y("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;null!=e.shape&&null==t&&(t=[null].concat(e.shape));let n=e.dtype;return null==n&&(n="float32"),new Nx({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}Nx.className="InputLayer",iu(Nx);class Tx{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Tx)for(const t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(null==e)return;for(const t of e)this.add(t.key,t.value)}}add(e,t,n){if(null!=this.id2Value[e.id])throw new $y(`Duplicate key: name=${e.name}, id=${e.id}`);return this.id2Value[e.id]=function(e,t){if(null==e.dtype||e.dtype===t.dtype)return t;try{return Lo(t,e.dtype)}catch(n){throw new $y(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}(e,t),this.name2Id[e.name]=e.id,null!=n&&(this.id2Mask[e.id]=n),this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return null!=this.id2Value[e.id]}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof bx){if(null==this.id2Value[e.id])throw new $y(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}{const t=this.name2Id[e];if(null==t)throw new $y(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof bx){if(null==this.id2Value[e.id])throw new $y(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}{const t=this.name2Id[e];if(null==t)throw new $y(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){null!=this.id2Mask&&vi(this.id2Mask)}}const Cx=new Ry,$x=new Ry;function Ex(e,t,n,r){const s=null!=n&&n.training,a=Array.isArray(e),i=a?e:[e],o=i.map((e=>e.name)),u=[],l=t.names();for(const e of o)-1!==l.indexOf(e)?u.push(t.getValue(e)):u.push(null);null!=r&&(r.maxNumTensors=-1/0,r.minNumTensors=1/0);const c=o.join(",")+"|"+t.names().sort().join(",");let h,p=Cx.get(c);if(null==p){const e=function(e,t){ie(null!=e&&e.length>0,(()=>"Expected at least one fetch, got none"));let n=[],r={};if(1===e.length){const s=Rx(e[0],t);n=s.sorted,r=s.recipientMap}else{const s=new Set;for(const a of e){const{sorted:e,recipientMap:i}=Rx(a,t);for(const t of e)s.has(t.name)||(n.push(t),s.add(t.name));for(const e in i)null==r[e]&&(r[e]=new Set),i[e].forEach((t=>r[e].add(t)))}}return{sorted:n,recipientCounts:Ax(r)}}(i,t);p=e.sorted,h=e.recipientCounts,Cx.put(c,p),$x.put(c,h)}h={},s||Object.assign(h,$x.get(c));const d=new Tx(t);for(let e=0;e<p.length;++e){if(null!=r){const e=bi().numTensors;e>r.maxNumTensors&&(r.maxNumTensors=e),e<r.minNumTensors&&(r.minNumTensors=e)}const a=p[e],i=a.sourceLayer;if(i instanceof Nx)continue;const l=[],c=[],f=[];let m=!1;for(const e of a.inputs){const n=d.getValue(e),r=d.getMask(e);l.push(n),c.push(r),null!=r&&(m=!0),s||(h[e.name]--,0!==h[e.name]||t.hasKey(e)||-1!==o.indexOf(e.name)||n.isDisposed||!0===e.sourceLayer.stateful||f.push(n))}m&&((n=n||{}).mask=c[0]);const g=My(i.apply(l,n));let y=null;i.supportsMasking&&(y=i.computeMask(l,c));const b=Ox(a),x=Array.isArray(b)?b:[b];for(let e=0;e<x.length;++e){d.hasKey(x[e])||d.add(x[e],g[e],Array.isArray(y)?y[0]:y);const t=o.indexOf(x[e].name);-1!==t&&(u[t]=g[e])}s||vi(f)}return d.disposeMasks(),a?u:u[0]}function Ax(e){const t={};for(const n in e)t[n]=e[n].size;return t}function Rx(e,t){const n=new Set,r=[],s={};for(const e of t.names())n.add(e);const a=[],i=[];for(a.push(e);a.length>0;){const e=a[a.length-1];if(n.has(e.name)){a.pop();continue}const t=i[i.length-1]===a.length-1;if(0===e.inputs.length||t)a.pop(),r.push(e),n.add(e.name),t&&i.pop();else{i.push(a.length-1);for(const t of e.inputs)null==s[t.name]&&(s[t.name]=new Set),s[t.name].add(e.name),n.has(t.name)||a.push(t)}}return{sorted:r,recipientMap:s}}function Ox(e){let t;if(1===e.sourceLayer.inboundNodes.length)t=e.sourceLayer.output;else{let n=null;for(let t=0;t<e.sourceLayer.inboundNodes.length;++t)for(const r of e.sourceLayer.inboundNodes[t].outputTensors)if(r.id===e.id){n=t;break}t=e.sourceLayer.getOutputAt(n)}return t}function Fx(e,t){return wi((()=>jo(Nh(Go(e,e),t,!0))))}Ye().registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",(()=>100),(function(e){null!=Cx&&Cx.setMaxEntries(e),null!=$x&&$x.setMaxEntries(e)}));class _x extends su{getConfig(){return{}}}class Dx extends _x{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return wi((()=>{const t=Fx(e,this.axis),n=Pc(t,0,this.maxValue);return Go(e,Vo(n,Wo(vb(),t)))}))}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}Dx.className="MaxNorm",iu(Dx);class Mx extends _x{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return wi((()=>Vo(e,Wo(vb(),Fx(e,this.axis)))))}getConfig(){return{axis:this.axis}}}Mx.className="UnitNorm",iu(Mx);class Lx extends _x{apply(e){return Gp(e)}}Lx.className="NonNeg",iu(Lx);class zx extends _x{constructor(e){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=null!=e.minValue?e.minValue:this.defaultMinValue,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.rate=null!=e.rate?e.rate:this.defaultRate,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return wi((()=>{const t=Fx(e,this.axis),n=Wo(Go(this.rate,Pc(t,this.minValue,this.maxValue)),Go(1-this.rate,t));return Go(e,Vo(n,Wo(vb(),t)))}))}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}zx.className="MinMaxNorm",iu(zx);const Px={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Bx(e){return By(e)}function Wx(e,t={}){return Uy(e,au.getMap().classNameMap,t,"constraint")}function Ux(e){return null==e?null:"string"==typeof e?Wx({className:e in Px?Px[e]:e,config:{}}):e instanceof _x?e:Wx(e)}function Vx(e){return new Dx(e)}function Gx(e){return new Mx(e)}function jx(){return new Lx}function Hx(e){return new zx(e)}function qx(){return new Ub}function Kx(){return new Vb}function Xx(e){return new Gb(e)}function Yx(e){return new jb(e)}function Jx(e){return new Hb(e)}function Zx(e){return new qb(e)}function Qx(e){return new Kb(e)}function ew(e){return new Xb(e)}function tw(e){return new Yb(e)}function nw(e){return new Jb(e)}function rw(e){return new Zb(e)}function sw(e){return new Qb(e)}function aw(e){return new ex(e)}function iw(e){return new tx(e)}function ow(e){return new nx(e)}async function uw(e){if(null==e)return;const t=[],n=[],r=[];for(const s in e){const a=e[s];if("number"!=typeof a){const e=a;t.push(e.data()),n.push(s),r.push(e)}}if(t.length>0){const s=await Promise.all(t);for(let t=0;t<s.length;++t)e[n[t]]=s[t][0];vi(r)}}function lw(e){if(null!=e)for(const t in e){const n=e[t];"number"!=typeof n&&n.dispose()}}var cw;!function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"}(cw||(cw={}));class hw{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}}class pw{constructor(e,t=10){null==e&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(const t of this.callbacks)t.setParams(e)}setModel(e){for(const t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onEpochBegin(e,t)}async onEpochEnd(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onEpochEnd(e,t)}async onBatchBegin(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onBatchBegin(e,t)}async onBatchEnd(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onBatchEnd(e,t)}async onTrainBegin(e){null==e&&(e={});for(const t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){null==e&&(e={});for(const t of this.callbacks)await t.onTrainEnd(e)}}class dw extends hw{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){null==t&&(t={});const n=null==t.size?0:t.size;this.seen+=n;for(const e in t){const r=t[e];if("number"==typeof r)this.totals.hasOwnProperty(e)||(this.totals[e]=0),this.totals[e]=this.totals[e]+r*n;else{let t;e in this.totals?t=this.totals[e]:this.totals[e]=0;const s=wi((()=>Wo(this.totals[e],Go(r,n))));this.totals[e]=s,null!=t&&t.dispose()}}}async onEpochEnd(e,t){if(null!=t)for(const e of this.params.metrics)null!=this.totals[e]&&("number"==typeof this.totals[e]?t[e]=this.totals[e]/this.seen:wi((()=>{const n=Go(Vo(1,this.seen),this.totals[e]);t[e]=n,this.totals[e].dispose(),ki(t[e])})))}}class fw extends hw{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){null==t&&(t={}),this.epoch.push(e);for(const e in t)null==this.history[e]&&(this.history[e]=[]),this.history[e].push(t[e])}async syncData(){const e=[],t=[],n=[];for(const r in this.history){const s=this.history[r];for(let a=0;a<s.length;++a)if("number"!=typeof s[a]){const i=s[a];e.push(i.data()),t.push(r),n.push(a)}}const r=await Promise.all(e);for(let e=0;e<r.length;++e)this.history[t[e]][n[e]].dispose(),this.history[t[e]][n[e]]=r[e][0]}}class mw extends hw{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||am,this.yieldEvery=t||"auto","auto"===this.yieldEvery&&(this.yieldEvery=125),"never"===this.yieldEvery&&null!=e.onYield)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");Re(this.yieldEvery)&&(this.maybeWait=function(e,t,n){let r,s=null!=n?n():Zs();return(...a)=>{const i=null!=n?n():Zs();return i-s<t||(s=i,r=e(...a)),r}}(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,n){const r=[];null!=this.yield&&(await uw(n),r.push(this.yield(e,t,n))),r.push(this.nextFrameFunc()),await Promise.all(r)}async onEpochBegin(e,t){this.currentEpoch=e,null!=this.epochBegin&&(await uw(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const n=[];null!=this.epochEnd&&(await uw(t),n.push(this.epochEnd(e,t))),"epoch"===this.yieldEvery&&n.push(this.nextFrameFunc()),await Promise.all(n)}async onBatchBegin(e,t){null!=this.batchBegin&&(await uw(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const n=[];null!=this.batchEnd&&(await uw(t),n.push(this.batchEnd(e,t))),"batch"===this.yieldEvery?n.push(this.nextFrameFunc()):Re(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){null!=this.trainBegin&&(await uw(e),await this.trainBegin(e))}async onTrainEnd(e){null!=this.trainEnd&&(await uw(e),await this.trainEnd(e))}}function gw(e,t){return null==e&&(e={}),e instanceof hw?[e]:Array.isArray(e)&&e[0]instanceof hw?e:My(e).map((e=>new mw(e,t)))}class yw{constructor(){}static registerCallbackConstructor(e,t){ie(e>=0&&Number.isInteger(e),(()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`)),yw.checkForDuplicate(t),null==yw.constructors[e]&&(yw.constructors[e]=[]),yw.constructors[e].push(t)}static checkForDuplicate(e){for(const t in yw.constructors)yw.constructors[+t].forEach((t=>{if(t===e)throw new $y("Duplicate callback constructor.")}))}static clear(){yw.constructors={}}static createCallbacks(e){const t=[];for(const n in yw.constructors){const r=+n;e>=r&&t.push(...yw.constructors[r])}return t.map((e=>new e))}}function bw(e,t,n,r,s,a,i,o,u){const l=new fw,c=[new dw,...yw.createCallbacks(t)];null!=e&&c.push(...e),c.push(l);const h=new pw(c);return h.setParams({epochs:n,initialEpoch:r,samples:s,steps:a,batchSize:i,verbose:t,doValidation:o,metrics:u}),{callbackList:h,history:l}}function xw(e,t={},n=!1){return Uy(e,au.getMap().classNameMap,t,"layer",n)}function ww(e,t){return wi((()=>{"float32"!==e.dtype&&(e=Lo(e,"float32"));const n=Nh(Fb(e),t,!0),r=cu(n.shape,vb()),s=jo(xu(n,r));return Vo(e,s)}))}function vw(e,t){return wi((()=>op(Fb(du(t,e)),-1)))}function kw(e,t){return wi((()=>op(mu(du(t,e)),-1)))}function Iw(e,t){return wi((()=>{const n=du(e,t),r=Pc(mu(e),vb(),Number.MAX_VALUE),s=mu(Vo(n,r));return Go(100,op(s,-1))}))}function Nw(e,t,n=!1){return wi((()=>{if(n)t=ld(t);else{const e=Nh(t,t.shape.length-1,!0);t=Vo(t,e)}return t=Pc(t,vb(),1-vb()),Xu(Nh(Go(Lo(e,"float32"),jh(t)),t.shape.length-1))}))}function Sw(e,t,n=!1){return wi((()=>{const r=Lo(Fh(function(e){const t=[gb(e.shape)];return vc(e,t)}(e)),"int32"),s=(t=Pc(t,vb(),1-vb())).shape;return Nw(vc(qu(r,s[s.length-1]),s),t,n)}))}function Tw(e,t){return wi((()=>{let n;return n=Pc(t,vb(),1-vb()),n=jh(Vo(n,du(1,n))),op(function(e,t){if(!pe(e.shape,t.shape))throw new $y(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return wi((()=>{const n=Gp(t),r=Xu(mu(t));return Wo(du(n,Go(t,e)),Hh($h(r)))}))}(e,n),-1)}))}function Cw(e,t){return wi((()=>{const n=ww(e,-1),r=ww(t,-1),s=Go(n,r);return Xu(Nh(s,-1))}))}yw.constructors={};const $w={meanSquaredError:vw,meanAbsoluteError:kw,meanAbsolutePercentageError:Iw,meanSquaredLogarithmicError:function(e,t){return wi((()=>{const n=Pc(t,vb(),Number.MAX_VALUE),r=jh(Wo(1,n)),s=Pc(e,vb(),Number.MAX_VALUE),a=jh(Wo(1,s));return op(Fb(du(r,a)),-1)}))},squaredHinge:function(e,t){return wi((()=>{const n=xu(0,du(1,Go(e,t)));return op(Fb(n),-1)}))},hinge:function(e,t){return wi((()=>{const n=xu(0,du(1,Go(e,t)));return op(n,-1)}))},categoricalHinge:function(e,t){return wi((()=>{const n=Nh(Go(e,t),-1),r=kh(Go(du(1,e),t),-1);return xu(0,Wo(1,du(r,n)))}))},logcosh:function(e,t){return wi((()=>{const n=Math.log(2),r=du(t,e),s=du(Wo(r,qh(Go(-2,r))),n);return op(s,-1)}))},categoricalCrossentropy:Nw,sparseCategoricalCrossentropy:Sw,binaryCrossentropy:Tw,kullbackLeiblerDivergence:function(e,t){return wi((()=>{const n=Pc(e,vb(),1),r=Pc(t,vb(),1);return Nh(Go(e,jh(Vo(n,r))),-1)}))},poisson:function(e,t){return wi((()=>{const n=jh(Wo(vb(),t));return op(du(t,Go(e,n)),-1)}))},cosineProximity:Cw};function Ew(e){if("string"==typeof e){if(e in $w)return $w[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new $y(t)}return e}function Aw(e,t){return wi((()=>{const n=Go(.5,bp(t)),r=kb(Dh(t,n),e.dtype);return op(ih(e,r),-1)}))}function Rw(e,t){return wi((()=>kb(ih(Ql(e,-1),Ql(t,-1)),"float32")))}function Ow(e,t){return wi((()=>Lo(Nh(Jh(ih(e,1),ih(t,1))),"float32")))}function Fw(e,t){return wi((()=>{const n=Ow(e,t),r=function(e,t){return wi((()=>Lo(Nh(Jh(ih(e,0),ih(t,1))),"float32")))}(e,t),s=Wo(n,r);return Lo(oh(Dh(s,0),Vo(n,s),0),"float32")}))}function _w(e,t){return Tw(e,t)}function Dw(e,t){return e.rank===t.rank&&(e=gd(e,[e.rank-1])),(t=Ql(t,-1)).dtype!==e.dtype&&(t=Lo(t,e.dtype)),Lo(ih(e,t),"float32")}const Mw=Nw,Lw=Sw,zw={binaryAccuracy:Aw,categoricalAccuracy:Rw,precision:Fw,categoricalCrossentropy:Mw,sparseCategoricalCrossentropy:Lw,mse:vw,MSE:vw,mae:kw,MAE:kw,mape:Iw,MAPE:Iw,cosine:Cw};function Pw(e){if("string"==typeof e&&e in zw)return zw[e];if("string"!=typeof e&&null!=e)return e;throw new $y(`Unknown metric ${e}`)}function Bw(e){if(Fy(null!==e,`Unknown LossOrMetricFn ${e}`),"string"==typeof e)return e;{let t;for(const n of Object.keys($w))if($w[n]===e){t=n;break}if(void 0!==t)return t;for(const n of Object.keys(zw))if(zw[n]===e){t=n;break}return void 0!==t?t:e.name}}var Ww=n(96763);function Uw(e,t,n=!1){if(null==e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype||!Vw(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){const n=JSON.stringify(e);n.length>1048576&&Ww.warn(`User-defined metadata of model "${t}" is too large in size (length=${n.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= 1048576.`)}}function Vw(e){if(null===e)return!0;if("object"==typeof e){if(Object.getPrototypeOf(e)===Object.prototype){const t=Object.keys(e);for(const n of t){if("string"!=typeof n)return!1;if(!Vw(e[n]))return!1}return!0}if(Array.isArray(e)){for(const t of e)if(!Vw(t))return!1;return!0}return!1}{const t=typeof e;return"string"===t||"number"===t||"boolean"===t}}var Gw=n(96763);function jw(e,t,n=Gw.log){let r="";for(let n=0;n<e.length;++n)n>0&&(r=r.slice(0,r.length-1)+" "),r+=e[n],r=r.slice(0,t[n]),r+=" ".repeat(t[n]-r.length);n(r)}function Hw(e,t,n){let r,s;try{s=e.inboundNodes.map((e=>JSON.stringify(e.inputShapes))).join(",")}catch(e){s="multiple"}try{r=JSON.stringify(e.outputShape)}catch(e){r="multiple"}jw([`${e.name} (${e.getClassName()})`,s,r,e.countParams().toString()],t,n)}function qw(e,t,n,r){let s,a;try{a=e.inboundNodes.map((e=>JSON.stringify(e.inputShapes))).join(",")}catch(e){a="multiple"}try{s=JSON.stringify(e.outputShape)}catch(e){s="multiple"}const i=[];for(const t of e.inboundNodes)if(!(null!=n&&n.length>0&&-1===n.indexOf(t)))for(let e=0;e<t.inboundLayers.length;++e){const n=t.inboundLayers[e].name,r=t.nodeIndices[e],s=t.tensorIndices[e];i.push(`${n}[${r}][${s}]`)}const o=e.name,u=e.getClassName(),l=0===i.length?"":i[0];jw([`${o} (${u})`,a,s,e.countParams().toString(),l],t,r);for(let e=1;e<i.length;++e)jw(["","","","",i[e]],t,r)}function Kw(e,t,n){return("inboundNodes"===e||"outputLayers"===e||"inputLayers"===e)&&0===t&&"string"==typeof n}function Xw(e,t){if(null===e)return null;if("string"==typeof e)return zy(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){const n=[],r=e.length;for(let s=0;s<r;++s){const r=e[s];Kw(t,s,r)?n.push(r):n.push(Xw(r,t))}return n}{const t={};for(const n of Object.keys(e)){const r=e[n];if("name"===n&&"string"==typeof r)t[n]=r;else{const e=zy(n);t[e]=Xw(r,e)}}return t}}function Yw(e,t){if(null==e)return null;if("string"==typeof e)return Ly(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){const n=[],r=e.length;for(let s=0;s<r;++s){const r=e[s];Kw(t,s,r)?n.push(r):n.push(Yw(r,t))}return n}{const t={};for(const n of Object.keys(e)){const r=e[n];t[Ly(n)]="name"!==n&&"className"!==n||"string"!=typeof r?Yw(r,n):r}return t}}const Jw="4.20.0";var Zw=n(96763);class Qw extends kx{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,null==this.name){const e=this.getClassName().toLowerCase();this.name=eb(e)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],Gy(this.inputs).length!==this.inputs.length)throw new $y(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map((e=>e.name))}`);Gy(this.outputs).length!==this.outputs.length&&Zw.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map((e=>e.name))}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const e of this.outputs){const t=e.sourceLayer,n=e.nodeIndex,r=e.tensorIndex;this.outputLayers.push(t),this.outputLayersNodeIndices.push(n),this.outputLayersTensorIndices.push(r)}for(const e of this.inputs){const t=e.sourceLayer,n=e.nodeIndex,r=e.tensorIndex;Fy(0===n,"input layer has >1 nodes"),Fy(0===r,"input layer has >1 tensors"),this.inputLayers.push(t),this.inputLayersNodeIndices.push(n),this.inputLayersTensorIndices.push(r)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let t=0;t<this.inputLayers.length;t++){const n=this.inputLayers[t];if(!(n instanceof Nx))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${t} (0-based) originates from layer type ${n.getClassName()}.`);this.inputNames.push(n.name),this.feedInputShapes.push(n.batchInputShape),this.feedInputNames.push(n.name)}for(const e of this.outputLayers)this.outputNames.push(e.name);this.internalInputShapes=this.inputs.map((e=>e.shape)),this.internalOutputShapes=this.outputs.map((e=>e.shape));const t={},n={},r={},s={},a={},i=[],o=(e,t,n,r,s,u)=>{null!=r&&null!=s&&null!=u||(r=e.sourceLayer,s=e.nodeIndex,u=e.tensorIndex);const l=r.inboundNodes[s];if(-1!==n.indexOf(l))throw new Cy(`The tensor ${e.name} at layer "${r.name}" is part of a cycle.`);if(-1!==t.indexOf(l))return;this.containerNodes.add(Qw.nodeKey(r,s)),r.id in a||(a[r.id]=Object.keys(a).length),-1===n.indexOf(l)&&n.push(l);const c=l.inboundLayers.length;for(let e=0;e<c;e++){const r=l.inputTensors[e],s=l.inboundLayers[e],a=l.nodeIndices[e],i=l.tensorIndices[e];o(r,t,n,s,a,i)}for(t.push(l);n.indexOf(l)>=0;)n.splice(n.indexOf(l),1);i.push(l)},u=[],l=[];for(const e of this.outputs)o(e,u,l);const c=i.slice().reverse();for(const e of c){n[e.id]=e,e.id in t||(t[e.id]=0);let a=t[e.id];const i=null==r[e.outboundLayer.id]?0:r[e.outboundLayer.id];a=Math.max(a,i),r[e.outboundLayer.id]=a,s[e.outboundLayer.id]=e.outboundLayer,t[e.id]=a;for(let r=0;r<e.inboundLayers.length;r++){const s=e.inboundLayers[r],i=e.nodeIndices[r],o=s.inboundNodes[i],u=null==t[o.id]?0:t[o.id];t[o.id]=Math.max(a+1,u),n[o.id]=o}}const h={};for(const e in t){const r=t[e];r in h||(h[r]=[]),h[r].push(n[e])}const p={};for(const e in r){const t=r[e];t in p||(p[t]=[]),p[t].push(s[e])}let d=Object.keys(p).map((e=>parseInt(e,10))).sort(Vy);this.layers=[];for(const e of d){const t=p[e];t.sort(((e,t)=>{const n=a[e.id],r=a[t.id];return n<r?-1:n>r?1:0}));for(const e of t)e instanceof Qw&&this.internalContainerRefs.push(e),this.layers.push(e)}this.layersByDepth=p,d=Object.keys(h).map((e=>parseInt(e,10))).sort(Vy);const f=this.inputs.slice(),m=[];for(const e of d)for(const t of h[e]){const e=t.outboundLayer;if(null!=e){for(const n of t.inputTensors)if(-1===f.indexOf(n))throw new Cy(`Graph disconnected: cannot obtain value for tensor ${n} at layer "${e.name}". The following previous layers were accessed without issue: ${m}`);for(const e of t.outputTensors)f.push(e);m.push(e.name)}}this.nodesByDepth=h;const g=this.layers.map((e=>e.name));for(const e of g){const t=g.filter((t=>t===e)).length;if(1!==t)throw new Cy(`The name "${e}" is used ${t} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new wx({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map((e=>null)),outputMasks:this.outputs.map((e=>null)),inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs.map((e=>e.shape))}),this.built=!0,this._refCount=1}assertNotDisposed(){if(0===this._refCount)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach((t=>{t._trainableWeights.forEach((t=>t.trainable=e))})),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new $y("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.layers)t.push(...e.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const n={};let r=0;const s=(e=>{const t=Object.keys(e);if(0===t.length)return!1;const n=t[0].split("/");return!isNaN(parseInt(n[n.length-1],10))})(e);s&&this.parseWeights(e);for(const e of this.layers)for(const[t,a]of e.weights.entries()){const e=s?`${a.name.split("/").slice(0,-1).join("/")+"/"}${t}`:a.originalName;if(null!=n[e])throw new $y(`Duplicate weight name: ${e}`);n[e]=a,r++}const a=[];for(const r in e){let s=r;if(null==n[r]){const e=r.split("/");s=e.slice(0,-2).concat([e[e.length-1]]).join("/")}if(null!=n[s])a.push([n[s],e[r]]);else if(t)throw new $y(`Provided weight data has no target variable: ${r}`);delete n[s]}if(t){const e=[];for(const t in n)e.push(t);if(e.length>0)throw new $y(`${e.length} of ${r} weights are not set: ${e}`)}mx(a)}parseWeights(e){for(const t in Object.keys(e)){const n=t.split("/"),r=["vars","layer_checkpoint_dependencies"],s=n.map((e=>e.startsWith("_")?e.slice(1):e)).filter((e=>!r.includes(e))).join("/");s!==t&&(e[s]=e[t],delete e[t])}}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${Jw}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=Yw(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return wi((()=>{e=My(e);const n=new Tx;for(let t=0;t<this.inputs.length;++t)n.add(this.inputs[t],e[t]);return Ex(this.outputs,n,t)}))}computeMask(e,t){return wi((()=>{let n;return e=My(e),n=null==t?Oy(null,e.length):My(t),this.runInternalGraph(e,n)[1]}))}computeOutputShape(e){const t=ux(e);if(t.length!==this.inputLayers.length)throw new $y(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let e=0;e<t.length;e++){const r=this.inputLayers[e],s=t[e];n[r.name+"_0_0"]=s}const r=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(Vy);if(r.length>1)for(const e of r){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer;if(-1!==this.inputLayers.map((e=>e.id)).indexOf(t.id))continue;const r=[];for(let t=0;t<e.inboundLayers.length;t++){const s=e.inboundLayers[t],a=e.nodeIndices[t],i=e.tensorIndices[t],o=n[`${s.name}_${a}_${i}`];r.push(o)}const s=ux(t.computeOutputShape(Dy(r))),a=t.inboundNodes.indexOf(e);for(let e=0;e<s.length;e++)n[`${t.name}_${a}_${e}`]=s[e]}}const s=[],a=[];for(let e=0;e<this.outputLayers.length;e++){const t=this.outputLayers[e],n=this.outputLayersNodeIndices[e],r=this.outputLayersTensorIndices[e],s=`${t.name}_${n}_${r}`;a.push(s)}for(let e=0;e<a.length;e++){const t=a[e];Fy(t in n),s.push(n[t])}return Dy(s)}runInternalGraph(e,t){null==t&&(t=Oy(null,e.length));const n={};for(let r=0;r<this.inputs.length;++r){const s=this.inputs[r],a=e[r],i=t[r];n[s.id]=[a,i]}const r=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(Vy);for(const e of r){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer,r=e.inputTensors,s=e.outputTensors,a=new Array;for(const e of r)e.id in n&&a.push(n[e.id]);if(a.length===r.length){let r,i,o,u,l={};if(null!=e.callArgs&&(l=e.callArgs),1===a.length){const[e,n]=a[0];null==l.mask&&(l.mask=n),o=My(t.call(e,l)),u=My(t.computeMask(e,n)),r=[e],i=[n]}else r=a.map((e=>e[0])),i=a.map((e=>e[1])),null==l.mask&&(l.mask=i),o=My(t.call(r,l)),u=My(t.computeMask(r,i));if(t.activityRegularizer)throw new Ey("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let e=0;e<s.length;++e){const t=s[e],r=o[e],a=u[e];n[t.id]=[r,a]}}}}const s=[],a=[],i=[];for(const e of this.outputs){Fy(e.id in n,`Could not compute output ${e.name} : ${e.id}`);const[t,r]=n[e.id];i.push(t.shape),s.push(t),a.push(r)}return[s,a,i]}buildNodeConversionMap(e){const t={};let n;for(const e of this.layers){n=e instanceof Qw?1:0;for(let r=0;r<e.inboundNodes.length;r++){const s=Qw.nodeKey(e,r);this.containerNodes.has(s)&&(t[s]=n,n+=1)}}return t}getLayer(e,t){if(null!=t)return this.findLayer(t);if(null==e)throw new $y("Provide either a layer name or layer index");if("number"==typeof e)return this.findLayer(e);for(const t of this.layers)if(t.name===e)return t;throw new $y(`No such layer: ${e}`)}findLayer(e){if(this.layers.length<=e)throw new $y(`Was asked to retrieve layer at index ${e}, but model only has ${this.layers.length} layer(s).`);return this.layers[e]}calculateLosses(){return wi((()=>{const e=[];for(const t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){const r=Qw.nodeKey(t,n);this.containerNodes.has(r)&&e.push(...t.calculateLosses())}return e}))}getConfig(){const e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(const e of this.layers){const r=e.getClassName(),s=e.getConfig(),a=[];for(let n=0;n<e.inboundNodes.length;n++){const r=e.inboundNodes[n],s=Qw.nodeKey(e,n);let i={};if(this.containerNodes.has(s)){if(r.callArgs)try{JSON.stringify(r.callArgs),i=r.callArgs}catch(t){Zw.warn(`Layer ${e.name} was passed non-serializable keyword arguments: ${r.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),i={}}if(r.inboundLayers.length>0){const e=[];for(let n=0;n<r.inboundLayers.length;n++){const s=r.inboundLayers[n],a=r.nodeIndices[n],o=r.tensorIndices[n];let u=t[Qw.nodeKey(s,a)];null==u&&(u=0),e.push([s.name,u,o,i])}a.push(e)}}}const i={};i.name=e.name,i.className=r,i.config=s,i.inboundNodes=a,n.push(i)}e.layers=n;const r=[];for(let e=0;e<this.inputLayers.length;e++){const n=this.inputLayers[e],s=this.inputLayersNodeIndices[e],a=Qw.nodeKey(n,s);if(!this.containerNodes.has(a))continue;let i=t[a];null==i&&(i=0);const o=this.inputLayersTensorIndices[e];r.push([n.name,i,o])}e.inputLayers=r;const s=[];for(let e=0;e<this.outputLayers.length;e++){const n=this.outputLayers[e],r=this.outputLayersNodeIndices[e],a=Qw.nodeKey(n,r);if(!this.containerNodes.has(a))continue;let i=t[a];null==i&&(i=0);const o=this.outputLayersTensorIndices[e];s.push([n.name,i,o])}return e.outputLayers=s,e}static fromConfig(e,t,n={},r=!1){const s={},a={};function i(e,t){e.name in a?a[e.name].push(t):a[e.name]=[t]}function o(e,t){const n=[];let r;for(const a of t){const o=a[0],u=a[1],l=a[2];if(r=null==a[3]?{}:a[3],!(o in s))return void i(e,t);const c=s[o];if(c.inboundNodes.length<=u)return void i(e,t);const h=c.inboundNodes[u];n.push(h.outputTensors[l])}n.length>0&&e.apply(Dy(n),r)}function u(e){const n=e.name,a=xw(e,null!=t.customObjects?t.customObjects:{});a.setFastWeightInitDuringBuild(r),s[n]=a,e.inboundNodes.forEach((e=>{if(!(e instanceof Array))throw new $y(`Corrupted configuration, expected array for nodeData: ${e}`);i(a,e)}))}const l=t.name,c=t.layers;for(const e of c)u(e);for(;!jy(a);)for(const e of c){const t=s[e.name];if(t.name in a){const e=a[t.name];delete a[t.name];for(const n of e)o(t,n)}}const h=[],p=[],d=t.inputLayers;for(const e of d){const t=e[0],n=e[1],r=e[2];Fy(t in s);const a=s[t].inboundNodes[n].outputTensors;h.push(a[r])}const f=t.outputLayers;for(const e of f){const t=e[0],n=e[1],r=e[2];Fy(t in s);const a=s[t].inboundNodes[n].outputTensors;p.push(a[r])}return new e({inputs:h,outputs:p,name:l})}get stateful(){if(this._stateful)throw new $y("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){wi((()=>{this.layers.forEach((e=>{e.stateful&&e.resetStates()}))}))}}function ev(e,t){return function(e,t,n){const r=t.length;if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>null));if(1===r)return Array.isArray(e)&&1===e.length?e:"object"==typeof e&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==r)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${r} outputs. Make sure a set of weights is provided for each model output.`);return e}if("object"==typeof e&&Object.keys(e).length>0&&"object"==typeof e[Object.keys(e)[0]]){const n=[];return t.forEach((t=>{t in e?n.push(e[t]):n.push(null)})),n}throw new Error(`The model has multiple (${r}) outputs, so ${n} must be either an array with ${r} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}(e,t,"classWeight")}async function tv(e,t,n,r){if(null!=t||null!=r)throw new Error("Support sampleWeight is not implemented yet");if(null!=n){const t=wi((()=>{if(1===e.shape.length)return zo(e);if(2===e.shape.length){if(e.shape[1]>1)return Ql(e,1);if(1===e.shape[1])return vc(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)})),r=Array.from(await t.data());vi(t);const s=[];return r.forEach((e=>{if(null==n[e])throw new Error(`classWeight must contain all classes in the training data. The class ${e} exists in the data but not in classWeight`);s.push(n[e])})),vd(s,"float32")}return null}function nv(e,t){return Go(e,t)}var rv=n(96763);function sv(e,t){let n,r;const s=t;n=s.xs,r=s.ys,ie(null!=n&&null!=r,(()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`));const a=av("input",e.inputNames,n),i=av("output",e.outputNames,r),o=a[0].shape[0];ie(a.length===e.inputs.length,(()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${a.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`)),ie(i.length===e.outputs.length,(()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${i.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`));for(let t=0;t<a.length;t++)ie(a[t].shape[0]===o,(()=>`Batch size mismatch: input ${e.inputNames[t]} has ${a[t].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`));for(let t=0;t<i.length;t++)ie(i[t].shape[0]===o,(()=>`Batch size mismatch: output ${e.outputNames[t]} has ${i[t].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`));return{xs:a,ys:i}}function av(e,t,n){if(n instanceof wa)return[n];if(Array.isArray(n))return ie(n.length===t.length,(()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`)),n;{const r=[];for(const s of t){if(null==n[s])throw new $y(`The feature data generated by the dataset lacks the required ${e} key '${s}'.`);r.push(n[s])}return r}}function iv(e){return"function"==typeof e.iterator}function ov(e){ie(e>0&&Number.isInteger(e),(()=>`batchSize is required to be a positive integer, but got ${e}`))}function uv(e,t,n){return null==e?[null]:Array.isArray(e)?e.map((e=>Nb(e,t,n-t))):Nb(e,t,n-t)}function lv(e,t){return wi((()=>null==e?null:Array.isArray(e)?e.map((e=>lv(e,t))):Ob(e,"int32"===t.dtype?t:Lo(t,"int32"))))}function cv(e,t){const n=[];let r=0,s=null;for(;r<e;)s=r+t,s>=e&&(s=e),n.push([r,s]),r=s;return n}function hv(e){const t=[];e instanceof wa&&(e=[e]);for(let n=0;n<e.length;++n){const r=e[n];if(1===r.rank)t.push(Ib(r,1));else{if(0===r.rank)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(r)}}return t}function pv(e,t){if(null==e)return;const n=[];if(t instanceof wa)n.push(t.id);else if(Array.isArray(t))t.forEach((e=>n.push(e.id)));else if(null!=t)for(const e in t){const r=t[e];n.push(r.id)}const r=[];if(e instanceof wa)-1===n.indexOf(e.id)&&r.push(e);else if(Array.isArray(e))e.forEach((e=>{-1===n.indexOf(e.id)&&r.push(e)}));else if(null!=e)for(const t in e){const s=e[t];-1===n.indexOf(s.id)&&r.push(s)}r.forEach((e=>{e.isDisposed||e.dispose()}))}var dv=n(96763);function fv(e){return Array.isArray(e)}function mv(e){return!function(e){return e instanceof wa}(e)&&!fv(e)}function gv(e,t,n,r=!0,s=""){if(null==t||0===t.length){if(null!=e){let t=!1;if(fv(e)&&e.length>0)t=!0;else if(mv(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new $y(`Error when checking model ${s} expected no data, but got ${e}`)}return[]}if(null==e)return t.map((e=>null));let a;if(mv(e)){a=[];for(const n of t){if(null==e[n])throw new $y(`No data provided for "${n}". Need data for each key in: ${t}`);a.push(e[n])}}else if(fv(e)){if(e.length!==t.length)throw new $y(`Error when checking model ${s}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);a=e}else{if(t.length>1)throw new $y(`The model ${s} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);a=[e]}if(a=hv(a),null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const i=a[e];if(i.shape.length!==n[e].length)throw new $y(`Error when checking ${s}: expected ${t[e]} to have ${n[e].length} dimension(s). but got array with shape ${i.shape}`);for(let t=0;t<n[e].length;++t){if(0===t&&!r)continue;const a=i.shape[t],o=n[e][t];if(null!=o&&o>=0&&a!==o)throw new $y(`${s} expected a batch of elements where each example has shape [${n[e].slice(1,n[e].length)}] (i.e.,tensor shape [*,${n[e].slice(1,n[e].length)}]) but the ${s} received an input with ${i.shape[0]} examples, each with shape [${i.shape.slice(1,i.shape.length)}] (tensor shape [${i.shape}])`)}}return a}function yv(e,t,n,r=!0,s=""){let a;if(Array.isArray(e)){if(e.length!==t.length)throw new $y(`Error when checking model ${s}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);a=e}else{if(t.length>1)throw new $y(`The model expects ${t.length} ${s} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);a=[e]}if(null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const i=a[e];if(i.shape.length!==n[e].length)throw new $y(`Error when checking ${s}: expected ${t[e]} to have ${n[e].length} dimension(s), but got array with shape ${JSON.stringify(i.shape)}`);for(let a=0;a<n[e].length;++a){if(0===a&&!r)continue;const o=i.shape[a],u=n[e][a];if(null!=u&&u!==o)throw new $y(`Error when checking ${s}: expected ${t[e]} to have shape ${JSON.stringify(n[e])} but got array with shape ${JSON.stringify(i.shape)}.`)}}}class bv extends Qw{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=dv.log){if(!this.built)throw new $y("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");!function(e,t,n,r=Gw.log){const s=function(e){let t=!0;const n=[],r=[];for(const t in e.nodesByDepth)n.push(e.nodesByDepth[t]);for(const e of n){if(e.length>1||1===e.length&&e[0].inboundLayers.length>1){t=!1;break}r.push(...e)}if(t)for(const n of e.layers){let e=!1;for(const s of n.inboundNodes)if(-1!==r.indexOf(s)){if(e){t=!1;break}e=!0}if(!t)break}return t}(e),a=["Layer (type)","Input Shape","Output shape","Param #"];let i;if(s?(t=t||90,n=n||[.32,.61,.89,1]):(t=t||115,n=n||[.24,.48,.7,.8,1]),n[n.length-1]<=1&&(n=n.map((e=>Math.floor(t*e)))),!s){a.push("Receives inputs"),i=[];for(const t in e.nodesByDepth)i.push(...e.nodesByDepth[t])}r("_".repeat(t)),jw(a,n,r),r("=".repeat(t));const o=e.layers;for(let e=0;e<o.length;++e)s?Hw(o[e],n,r):qw(o[e],n,i,r),r((e===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();const u=function(e){let t;return t=null!=e.collectedTrainableWeights?hx(e.collectedTrainableWeights):hx(e.trainableWeights),t}(e),l=hx(e.nonTrainableWeights);r(`Total params: ${u+l}`),r(`Trainable params: ${u}`),r(`Non-trainable params: ${l}`),r("_".repeat(t))}(this,e,t,n)}compile(e){if(null==e.loss&&(e.loss=[]),this.loss=e.loss,"string"==typeof e.optimizer)this.optimizer_=function(e){const t={Adagrad:()=>rm.adagrad(.01),Adadelta:()=>rm.adadelta(1,.95,vb()),Adam:()=>rm.adam(.001,.9,.999,vb()),Adamax:()=>rm.adamax(.002,.9,.999,vb(),0),RMSProp:()=>rm.rmsprop(.001,.9,0,vb()),SGD:()=>rm.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new $y(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof uu))throw new $y("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(Array.isArray(e.loss)||"string"==typeof e.loss||"function"==typeof e.loss)if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new $y(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);const n=e.loss;t=n.map((e=>Ew(e)))}else{const n=Ew(e.loss);this.outputs.forEach((e=>{t.push(n)}))}else{e.loss=e.loss;for(const t in e.loss)if(-1===this.outputNames.indexOf(t))throw new $y(`Unknown entry in loss dictionary: "${t}". Only expected the following keys: ${this.outputNames}`);for(const n of this.outputNames)null==e.loss[n]&&dv.warn(`Output "${n}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${n} during training`),t.push(Ew(e.loss[n]))}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let e=0;e<this.outputs.length;++e){const t=this.internalOutputShapes[e],n=this.outputNames[e];this.feedOutputNames.push(n),this.feedOutputShapes.push(t),this.feedLossFns.push(this.lossFunctions[e])}const n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],hb("loss",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;const t=this.lossFunctions[e];this.outputs.length>1&&(this.metricsTensors.push([t,e]),this.metricsNames.push(this.outputNames[e]+"_loss"))}}));const r=function(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>[]));let n;if("string"==typeof e||"function"==typeof e)n=[e];else{if(!Array.isArray(e)&&"object"!=typeof e)throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);n=e}if(Array.isArray(n))return t.map((e=>n));{const e=[];for(const r of t){let t=n.hasOwnProperty(r)?n[r]:[];Array.isArray(t)||(t=[t]),e.push(t)}return e}}(e.metrics,this.outputNames),s=(e,t,n)=>{this.outputNames.length>1&&(t=this.outputNames[e]+"_"+t),this.metricsNames.push(t),this.metricsTensors.push([n,e])};hb("metric",(()=>{for(let e=0;e<this.outputs.length;++e)-1===n.indexOf(e)&&(t=>{let n,r,a;for(const i of t){if("string"==typeof i&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(i)){const t=this.internalOutputShapes[e];let s;1===t[t.length-1]||this.lossFunctions[e]===Tw?-1!==["accuracy","acc"].indexOf(i)?r=Aw:-1!==["crossentropy","ce"].indexOf(i)&&(r=_w):this.lossFunctions[e]===Sw?-1!==["accuracy","acc"].indexOf(i)?r=Dw:-1!==["crossentropy","ce"].indexOf(i)&&(r=Lw):-1!==["accuracy","acc"].indexOf(i)?r=Rw:-1!==["crossentropy","ce"].indexOf(i)&&(r=Mw),-1!==["accuracy","acc"].indexOf(i)?s="acc":-1!==["crossentropy","ce"].indexOf(i)&&(s="ce"),a=r,n=""+s}else{const e=Pw(i);a=e,n=""+Bw(i)}let t;hb(n,(()=>{t=a})),s(e,n,t)}})(r[e])})),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&dv.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){const r=null==n.batchSize?32:n.batchSize;ov(r);const s=this.standardizeUserDataXY(e,t,!0,r);try{const e=s[0].concat(s[1]);this.makeTestFunction();const t=this.testFunction;return Dy(this.testLoop(t,e,r,n.verbose,n.steps))}finally{pv(s[0],e),pv(s[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),async function(e,t,n){const r=null!=(n=n||{}).batches,s=e.testFunction;let a=[];if(n.verbose>0)throw new Ey("Verbose mode is not implemented yet.");ie(!r||n.batches>0&&Number.isInteger(n.batches),(()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`));const i="function"==typeof t.next?t:await t.iterator();let o=0,u=0;for(;!r||u<n.batches;){const t=await i.next();if(a=wi((()=>{if(t.value){const{xs:n,ys:r}=sv(e,t.value),i=n.concat(r),l=wi((()=>s(i)));if(vi(i),0===u)for(let e=0;e<l.length;++e)a.push(tu(0));const c=i[0].shape[0];for(let e=0;e<l.length;++e){const t=l[e],n=a[e];a[e]=wi((()=>Wo(a[e],Go(c,t)))),u>0&&vi(n)}vi(l),o+=c,++u}return a})),t.done){r&&rv.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let e=0;e<a.length;++e){const t=a[e];a[e]=Vo(a[e],o),vi(t)}return Dy(a)}(this,e,t)}checkNumSamples(e,t,n,r="steps"){let s;if(null!=n){if(s=null,null!=t)throw new $y(`If ${r} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else{if(null==e)throw new $y(`Either the input data should have a defined shape, or ${r} shoud be specified.`);s=Array.isArray(e)?e[0].shape[0]:e.shape[0]}return s}execute(e,t){if(Array.isArray(t)&&0===t.length)throw new $y("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),r=n?t:[t],s=this.retrieveSymbolicTensors(r),a=new Tx;if(e instanceof wa&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new $y(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let t=0;t<this.inputs.length;++t)a.add(this.inputs[t],e[t])}else for(const t of this.inputs){const n=e[t.name];if(null==n)throw new $y(`No value is provided for the model's input ${t.name}`);a.add(t,n)}const i=Ex(s,a);return n?i:i[0]}retrieveSymbolicTensors(e){const t=Oy(null,e.length);let n=e.length;for(const r of this.layers){const s=Array.isArray(r.output)?r.output:[r.output],a=s.map((e=>e.name));for(let r=0;r<e.length;++r){const i=a.indexOf(e[r]);if(-1!==i&&(t[r]=s[i],n--),0===n)break}if(0===n)break}if(n>0){const n=[];throw t.forEach(((t,r)=>{null==t&&n.push(e[r])})),new $y(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return wi((()=>{const r=this.checkNumSamples(e);if(n)throw new Ey("Verbose predictLoop() is not implemented yet.");const s=cv(r,t),a=this.outputs.map((e=>[]));for(let t=0;t<s.length;++t)wi((()=>{const n=s[t][0],r=s[t][1],a=uv(e,n,r),i=[];if(Array.isArray(a))for(let e=0;e<a.length;++e)i.push({key:this.inputs[e],value:a[e]});else i.push({key:this.inputs[0],value:a});const o=new Tx(i);return Ex(this.outputs,o)})).forEach(((e,t)=>a[t].push(e)));return Dy(a.map((e=>Nc(e,0))))}))}predict(e,t={}){const n=hv(e);yv(n,this.inputNames,this.feedInputShapes,!1);try{const e=null==t.batchSize?32:t.batchSize;return ov(e),this.predictLoop(n,e)}finally{pv(n,e)}}predictOnBatch(e){yv(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,r){if(null==this.optimizer_)throw new Cy("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const s=[];for(let e=0;e<this.feedOutputShapes.length;++e){const t=this.feedOutputShapes[e];this.feedLossFns[e]===Sw?s.push(t.slice(0,t.length-1).concat([1])):s.push(t)}if(function(e,t,n){const r=Gy(e.map((e=>e.shape[0])));r.sort();const s=Gy(t.map((e=>e.shape[0])));if(s.sort(),r.length>1)throw new $y(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map((e=>e.shape)))}`);if(s.length>1)throw new $y(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map((e=>e.shape)))}`);if(r.length>0&&s.length>0&&!pe(r,s))throw new $y(`Input Tensors should have the same number of samples as target Tensors. Found ${r[0]} input sample(s) and ${s[0]} target sample(s).`)}(e=gv(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=gv(t,this.feedOutputNames,s,!1,"target")),function(e,t,n){const r=[vw,Tw,Nw];for(let s=0;s<e.length;++s){const a=e[s],i=t[s],o=n[s];if(null!=i){if(i===Nw&&1===a.shape[a.shape.length-1])throw new $y(`You are passing a target array of shape ${a.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(-1!==r.indexOf(i)){const e=a.shape.slice(1),t=o.slice(1);for(let n=0;n<e.length;++n){const r=e[n],s=t[n];if(null!=s&&r!==s)throw new $y(`A target Tensor with shape ${a.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=r&&r>0&&e[0].shape[0]%r!=0)throw new $y(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${r}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,r,s=!0,a){const[i,o]=this.standardizeUserDataXY(e,t,s,a);if(null!=n)throw new Error("sample weight is not supported yet.");let u=null;if(null!=r){const e=ev(r,this.outputNames);u=[];for(let t=0;t<e.length;++t)u.push(await tv(o[t],null,e[t]))}return[i,o,u]}testLoop(e,t,n,r=0,s){return wi((()=>{const a=this.checkNumSamples(t,n,s,"steps"),i=[];if(r>0)throw new Ey("Verbose mode is not implemented yet.");if(null!=s)throw new Ey("steps mode in testLoop() is not implemented yet");{const r=cv(a,n),s=vd(xb(0,a));for(let n=0;n<r.length;++n){const a=r[n][0],o=r[n][1],u=Nb(s,a,o-a),l=lv(t,u),c=e(l);if(0===n)for(let e=0;e<c.length;++e)i.push(tu(0));for(let e=0;e<c.length;++e){const t=c[e];i[e]=Wo(i[e],Go(o-a,t))}}for(let e=0;e<i.length;++e)i[e]=Vo(i[e],a)}return i}))}getDedupedMetricsNames(){const e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){const r=e[n];let s=r;_y(e,r)>1&&(s+=`_${_y(e.slice(0,n),r)}`),t.push(s)}return t}makeTrainFunction(){return e=>{const t=[],n=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+2*this.outputs.length),a=[],i=this.collectedTrainableWeights.map((e=>e.read()));return[this.optimizer_.minimize((()=>{const e=[];for(let t=0;t<this.inputs.length;++t)e.push({key:this.inputs[t],value:n[t]});const i=new Tx(e),o=Ex(this.outputs,i,{training:!0});let u;for(let e=0;e<this.lossFunctions.length;++e){let n=(0,this.lossFunctions[e])(r[e],o[e]);null!=s[e]&&(n=nv(n,s[e]));const a=op(n);t.push(a),u=0===e?n:Wo(u,n)}for(let e=0;e<this.metricsTensors.length;++e){let n;if(this.outputs.length>1&&e<this.outputs.length)n=t[e];else{const t=this.metricsTensors[e][0],s=this.metricsTensors[e][1];n=op(t(r[s],o[s]))}ki(n),a.push(n)}return u=op(u),this.calculateLosses().forEach((e=>{u=Wo(u,e)})),u}),!0,i)].concat(a)}}makeTestFunction(){this.testFunction=e=>wi((()=>{const t=[];let n;const r=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let e=0;e<this.inputs.length;++e)a.push({key:this.inputs[e],value:r[e]});const i=new Tx(a),o=Ex(this.outputs,i);for(let e=0;e<this.lossFunctions.length;++e){const r=this.lossFunctions[e],a=op(r(s[e],o[e]));n=0===e?a:Wo(n,a),t.push(n)}for(let e=0;e<this.metricsTensors.length;++e){const n=this.metricsTensors[e][0],r=this.metricsTensors[e][1],a=op(n(s[r],o[r]));t.push(a)}return t}))}async fit(e,t,n={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");let r,s,a,i,o,u,l,c,h;this.isTraining=!0;try{const p=null==n.batchSize?32:n.batchSize;ov(p);const d=!1,f=await this.standardizeUserData(e,t,n.sampleWeight,n.classWeight,d,p);r=f[0],s=f[1],h=f[2];let m,g=!1;if(null!=n.validationData&&n.validationData.length>0){if(g=!0,2!==n.validationData.length)throw 3===n.validationData.length?new Ey("validationData including sample weights is not supported yet."):new $y(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);o=n.validationData[0],u=n.validationData[1];const e=!0,t=await this.standardizeUserData(o,u,null,null,e,p);l=t[0],c=t[1],m=l.concat(c)}else if(null!=n.validationSplit&&n.validationSplit>0&&n.validationSplit<1){g=!0;const e=Math.floor(r[0].shape[0]*(1-n.validationSplit)),t=r[0].shape[0];l=uv(r,e,t),a=r,r=uv(r,0,e),c=uv(s,e,t),i=s,s=uv(s,0,e),m=l.concat(c)}else null!=n.validationSteps&&(g=!0);const y=r.concat(s).concat(h);this.checkTrainableWeightsConsistency();const b=this.makeTrainFunction(),x=this.getDedupedMetricsNames();let w,v;g?(this.makeTestFunction(),w=this.testFunction,v=x.slice().concat(x.map((e=>"val_"+e)))):(w=null,m=[],v=x.slice());const k=gw(n.callbacks,n.yieldEvery);return await this.fitLoop(b,y,x,p,n.epochs,n.verbose,k,w,m,n.shuffle,v,n.initialEpoch,null,null)}finally{this.isTraining=!1,pv(r,e),pv(s,t),pv(a,e),pv(i,t),pv(l,o),pv(c,u),null!=h&&vi(h)}}async fitLoop(e,t,n,r,s,a,i,o,u,l,c,h,p,d){null==r&&(r=32),null==s&&(s=1),null==l&&(l=!0),null==h&&(h=0);let f=!1;if(null!=o&&null!=u&&(f=!0),null!=d&&(f=!0,null==p))throw new $y("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const m=this.checkNumSamples(t,r,p,"steps_per_epoch");let g;null!=m&&(g=xb(0,m)),null==a&&(a=1);const{callbackList:y,history:b}=bw(i,a,s,h,m,p,r,f,c);y.setModel(this),this.history=b,await y.onTrainBegin(),this.stopTraining_=!1;for(let a=h;a<s;++a){await y.onEpochBegin(a);const s={};if(null!=p)throw new Ey("stepsPerEpoch mode is not implemented yet.");{if("batch"===l)throw new Ey("batch shuffling is not implemneted yet");l&&Z(g);const a=vd(g),i=cv(m,r);for(let l=0;l<i.length;++l){const c={};if(await y.onBatchBegin(l,c),wi((()=>{const h=i[l][0],p=i[l][1],d=Nb(a,h,p-h);c.batch=l,c.size=p-h;const m=lv(t,d),g=e(m);for(let e=0;e<n.length;++e){const t=n[e],r=g[e];c[t]=r,ki(r)}if(l===i.length-1&&f){const e=this.testLoop(o,u,r);for(let t=0;t<n.length;++t){const r=n[t],a=e[t];ki(a),s["val_"+r]=a}}})),await y.onBatchEnd(l,c),lw(c),this.stopTraining_)break}a.dispose()}if(await y.onEpochEnd(a,s),this.stopTraining_)break}return await y.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(e,t){return async function(e,t,n){const r=null!=n.batchesPerEpoch;if(ie(null!=e.optimizer,(()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig).")),ie(null!=n,(()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call.")),ie(null!=n.epochs&&n.epochs>0&&Number.isInteger(n.epochs),(()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`)),ie(!r||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),(()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`)),ie(null==n.validationSplit,(()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead.")),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{const s=null!=n.validationData;let a,i;if(s)if(iv(n.validationData))ie(null==n.validationBatches||n.validationBatches>0&&Number.isInteger(n.validationBatches),(()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`));else{const e=function(e){if(3===e.length)throw new Ey("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}(n.validationData);a=e.xs,i=e.ys}const o=e.makeTrainFunction(),u=e.getDedupedMetricsNames();let l;l=s?u.slice().concat(u.map((e=>"val_"+e))):u.slice();const c=gw(n.callbacks,n.yieldEvery),h=null==n.verbose?1:n.verbose,{callbackList:p,history:d}=bw(c,h,n.epochs,null,null,function(e,t){let n=null;return null!=t.batchesPerEpoch?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}(t,n),null,s,l);p.setModel(e),e.history=d,await p.onTrainBegin(),e.stopTraining_=!1;let f=null==n.initialEpoch?0:n.initialEpoch,m=await t.iterator();for(;f<n.epochs;){const l={};await p.onEpochBegin(f);let c=0,h=0;for(r||(m=await t.iterator());!r||c<n.batchesPerEpoch;){const t=await m.next();if(r&&t.done){rv.warn(`You provided \`batchesPerEpoch\` as ${n.batchesPerEpoch}, but your dataset iterator ran out of data after ${c} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, `+n.batchesPerEpoch*n.epochs+" batches). You may need to use the repeat() function when building your dataset.");break}if(null!=t.value){const{xs:r,ys:s}=sv(e,t.value),a={};a.batch=h,a.size=r[0].shape[0],await p.onBatchBegin(h,a);const i=[];if(null!=n.classWeight){const t=ev(n.classWeight,e.outputNames);for(let e=0;e<t.length;++e)i.push(await tv(s[e],null,t[e]))}const l=r.concat(s).concat(i),d=o(l);vi(l);for(let e=0;e<u.length;++e){const t=u[e],n=d[e];a[t]=n,ki(n)}await p.onBatchEnd(h,a),lw(a),h++,c++}if(r?c>=n.batchesPerEpoch:t.done){if(s){let t;t=iv(n.validationData)?My(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):My(e.evaluate(a,i,{batchSize:null==n.validationBatchSize?32:n.validationBatchSize,verbose:0}));for(let n=0;n<e.metricsNames.length;++n)l[`val_${e.metricsNames[n]}`]=t[n]}break}if(e.stopTraining_)break}if(await p.onEpochEnd(f,l),f++,e.stopTraining_)break}return await p.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}(this,e,t)}async trainOnBatch(e,t){const n=await this.standardizeUserData(e,t),r=n[0],s=n[1],a=this.makeTrainFunction()(r.concat(s)),i=[];for(const e of a){const t=await e.data();i.push(t[0])}return vi(a),pv(n[0],e),pv(n[1],t),Dy(i)}getNamedWeights(e){const t=[],n=null!=e&&e.trainableOnly,r=n?this.trainableWeights:this.weights,s=this.getWeights(n);for(let e=0;e<r.length;++e)n&&!r[e].trainable||t.push({name:r[e].originalName,tensor:s[e]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){const e=super.dispose();if(0===e.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){const t=bi().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-bi().numTensors}return e}getLossIdentifiers(){let e;if("string"==typeof this.loss)e=Ly(this.loss);else if(Array.isArray(this.loss)){for(const e of this.loss)if("string"!=typeof e)throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map((e=>Ly(e)))}else{const t=Object.keys(this.loss);e={};const n=this.loss;for(const r of t){if("string"!=typeof n[r])throw new Error("Serialization of non-string loss is not supported.");e[r]=Ly(n[r])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[Ly(Bw(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((e=>Ly(Bw(e))));{const e={};for(const t in this.metrics)e[t]=Ly(Bw(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(null!=e.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=e.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=e.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");const t=xw(Xw(e.optimizer_config));let n,r;if("string"==typeof e.loss)n=zy(e.loss);else if(Array.isArray(e.loss))n=e.loss.map((e=>zy(e)));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=zy(e.loss[t])}if(Array.isArray(e.metrics))r=e.metrics.map((e=>zy(e)));else if(null!=e.metrics){r={};for(const t in e.metrics)r[t]=zy(e.metrics[t])}this.compile({loss:n,metrics:r,optimizer:t})}async save(e,t){if("string"==typeof e){const t=to(e);if(0===t.length)throw new $y(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new $y(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new $y("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const n=await Di(this.getNamedWeights(t)),r={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:`TensorFlow.js tfjs-layers v${Jw}`,convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){r.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:s}=await Di(await this.optimizer.getWeights(),e);n.specs.push(...s),n.data=ji([n.data,t])}if(null!=this.userDefinedMetadata){const e=!0;Uw(this.userDefinedMetadata,this.name,e),r.userDefinedMetadata=this.userDefinedMetadata}return r.weightData=n.data,r.weightSpecs=n.specs,e.save(r)}setUserDefinedMetadata(e){Uw(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}bv.className="Model",iu(bv);class xv extends bv{}xv.className="Functional",iu(xv);var wv=n(96763);async function vv(e,t){"modelTopology"in e||(e={modelTopology:e});let n=e.modelTopology;null!=n.model_config&&(n=n.model_config);const r=xw(Xw(n),t);if(null!=e.weightsManifest){const t=await Ru(e.weightsManifest,e.pathPrefix,r.weights.map((e=>e.originalName))),n={};for(const e of r.weights)n[e.originalName]=t[e.originalName];r.loadWeights(n),vi(t)}return r}async function kv(e,t){if(null==t&&(t={}),"string"==typeof e){const n=no(e,t);if(0===n.length)n.push(Lu(e,t));else if(n.length>1)throw new $y(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return async function(e,t,n){if(null==n&&(n={}),null==e.load)throw new $y("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const r=await e.load();let s=r.modelTopology;null!=s.model_config&&(s=s.model_config);const a=null==n.strict||n.strict,i=null!=r.weightData&&null!=r.weightSpecs&&a,o=xw(Xw(s),void 0,i),u=r.trainingConfig;if(null!=u&&o.loadTrainingConfig(u),null!=r.userDefinedMetadata&&o.setUserDefinedMetadata(r.userDefinedMetadata),null!=r.weightData){if(null==r.weightSpecs)throw new $y("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:e,optimizerWeights:t}=function(e,t){const n=Mi(e,t),r={},s=[];return t.forEach((e=>{"optimizer"===e.group?s.push({name:e.name,tensor:n[e.name]}):r[e.name]=n[e.name]})),{modelWeights:r,optimizerWeights:s}}(r.weightData,r.weightSpecs);o.loadWeights(e,a),null!=o.optimizer&&t.length>0&&await o.optimizer.setWeights(t),vi(e),vi(t.map((e=>e.tensor)))}return o}(e,0,t)}class Iv extends bv{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=null!=e.name?e.name:eb("sequential_"),null!=e.layers)for(const t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some((e=>e<0)))throw new $y(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof Iv||e instanceof bv;let n;if(t){if(n=e,1!==n.outputs.length)throw new $y("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==n.inputs.length)throw new $y("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===e.inboundNodes.length){if(null==e.batchInputShape)throw new $y("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const t=Sx({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(t)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==e.inboundNodes.length)throw new $y(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(1!==e.inboundNodes[0].outputTensors.length)throw new $y("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=Ix(this.outputs[0])}this.inboundNodes=[],new wx({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Oy(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs[0].shape})}else{const t=e.apply(this.outputs[0]);if(Array.isArray(t))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[t],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return null==this.model&&this.build(),this.model.call(e,t)}build(e){if(cx(e),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new bv({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=wv.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){null==this.model&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new Cy("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new Cy("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return null==this.model&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return null==this.model&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return null==this.model?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new Cy("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new Cy("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},r=!1){let s,a={};if(t instanceof Array){if(null==t[0].className||"Merge"===t[0].className)throw new $y("Legacy serialization format not supported yet.");s=t}else ie(null!=t.layers,(()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field.")),s=t.layers,delete t.layers,a=t;const i=new e(a);if(!(i instanceof Iv))throw new Ey(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(const e of s){const t=xw(e,void 0,r);r&&t.setFastWeightInitDuringBuild(!0),i.add(t)}return i}set stopTraining(e){if(null==this.model)throw new $y("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(null==this.model)throw new $y("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}}function Nv(e){return new bv(e)}function Sv(e){return new Iv(e)}function Tv(e){return Sx(e)}function Cv(e,t){yw.registerCallbackConstructor(e,t)}Iv.className="Sequential",iu(Iv);class $v extends su{getConfig(){return{}}}class Ev extends $v{apply(e,t=1){return function(e,t=1){if(1!==t)throw new Ey(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return hh(e)}(e,t)}}Ev.className="elu",iu(Ev);class Av extends $v{apply(e){return Qp(e)}}Av.className="selu",iu(Av);class Rv extends $v{apply(e){return Gp(e)}}Rv.className="relu",iu(Rv);class Ov extends $v{apply(e){return wi((()=>hp(6,Gp(e))))}}Ov.className="relu6",iu(Ov);class Fv extends $v{apply(e){return e}}Fv.className="linear",iu(Fv);class _v extends $v{apply(e){return Sc(e)}}_v.className="sigmoid",iu(_v);class Dv extends $v{apply(e){return function(e){return wi((()=>{const t=Wo(.5,Go(.2,e));return Pc(t,0,1)}))}(e)}}Dv.className="hardSigmoid",iu(Dv);class Mv extends $v{apply(e){return qh(e)}}Mv.className="softplus",iu(Mv);class Lv extends $v{apply(e){return function(e){return wi((()=>Vo(e,Wo(mu(e),1))))}(e)}}Lv.className="softsign",iu(Lv);class zv extends $v{apply(e){return Cc(e)}}zv.className="tanh",iu(zv);class Pv extends $v{apply(e,t=-1){return ld(e,t)}}Pv.className="softmax",iu(Pv);class Bv extends $v{apply(e,t=-1){return Xh(e,t)}}Bv.className="logSoftmax",iu(Bv);class Wv extends $v{apply(e){return wi((()=>wi((()=>{const t=Math.sqrt(2),n=Go(.5,Wo(1,dh(Vo(e,t))));return Go(e,n)}))))}}Wv.className="gelu",iu(Wv);class Uv extends $v{apply(e){return wi((()=>Go(.5,Go(e,Wo(1,Cc(Go(jo(Vo(2,Math.PI)),Wo(e,Go(.044715,pu(e,3))))))))))}}Uv.className="gelu_new",iu(Uv);class Vv extends $v{apply(e){return wi((()=>Go(e,Cc(qh(e)))))}}Vv.className="mish",iu(Vv);class Gv extends $v{apply(e,t=1){return wi((()=>Go(Sc(Go(e,t)),e)))}}function jv(e){return e.getClassName()}function Hv(e,t={}){return Uy(e,au.getMap().classNameMap,t,"activation")}function qv(e){if(null==e){return Hv({className:"linear",config:{}})}if("string"==typeof e){const t={};return t.className=e,t.config={},Hv(t)}return e instanceof $v?e:Hv(e)}function Kv(e){if(null!=e&&"object"!=typeof e)throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}Gv.className="swish",iu(Gv);class Xv extends su{}class Yv extends Xv{constructor(e){super(),Kv(e),this.l1=null==e||null==e.l1?.01:e.l1,this.l2=null==e||null==e.l2?.01:e.l2,this.hasL1=0!==this.l1,this.hasL2=0!==this.l2}apply(e){return wi((()=>{let t=up([1]);return this.hasL1&&(t=Wo(t,Nh(Go(this.l1,mu(e))))),this.hasL2&&(t=Wo(t,Nh(Go(this.l2,Fb(e))))),vc(t,[])}))}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}Yv.className="L1L2",iu(Yv);const Jv={l1l2:"L1L2"};function Zv(e){return By(e)}function Qv(e,t={}){return Uy(e,au.getMap().classNameMap,t,"regularizer")}function ek(e){return null==e?null:"string"==typeof e?Qv({className:e in Jv?Jv[e]:e,config:{}}):e instanceof Xv?e:Qv(e)}class tk extends kx{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=lx(e);let n=Gp(e);return null!=this.maxValue&&(n=Pc(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}tk.className="ReLU",iu(tk);class nk extends kx{constructor(e){super(null==e?{}:e),this.DEFAULT_ALPHA=.3,null==e&&(e={}),this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=lx(e);return Bh(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}nk.className="LeakyReLU",iu(nk);class rk extends kx{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=ix(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=ek(e.alphaRegularizer),this.alphaConstraint=Ux(e.alphaConstraint),null==e.sharedAxes)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else{if("number"!=typeof e.sharedAxes)throw new $y(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=cx(e)).slice(1);if(null!=this.sharedAxes)for(const e of this.sharedAxes)t[e-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const n={};if(null!=this.sharedAxes)for(let t=1;t<e.length;++t)n[t]=e[t];this.inputSpec=[new yx({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=lx(e),Cp(e,this.alpha.read())}getConfig(){const e={alphaInitializer:ax(this.alphaInitializer),alphaRegularizer:Zv(this.alphaRegularizer),alphaConstraint:Bx(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}rk.className="PReLU",iu(rk);class sk extends kx{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==this.DEFAULT_ALPHA)throw new Ey(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=lx(e);return hh(n)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}sk.className="ELU",iu(sk);class ak extends kx{constructor(e){super(null==e?{}:e),this.DEFAULT_THETA=1,null==e&&(e={}),this.theta=null==e.theta?this.DEFAULT_THETA:e.theta}call(e,t){const n=lx(e);return Go(n,Lo(Dh(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}ak.className="ThresholdedReLU",iu(ak);class ik extends kx{constructor(e){super(null==e?{}:e),this.DEFAULT_AXIS=1,null==e&&(e={}),this.softmax=(new Pv).apply,this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis}call(e,t){return wi((()=>{let n=lx(e);const r=t.mask;if(null!=r){const e=Go(du(lp(n.shape),Lo(r,n.dtype)),tu(-1e9));n=Wo(n,e)}return this.axis instanceof Array?this.axis.length>1?$h(du(n,Yh(n,this.axis,!0))):this.softmax(n,this.axis[0]):this.softmax(n,this.axis)}))}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function ok(e,t,n){if("number"==typeof e)return Oy(e,t);if(e.length!==t)throw new $y(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let s=0;s<t;++s){const a=e[s];if((r=a)!==parseInt(r.toString(),10))throw new $y(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${a}`)}return e;var r}function uk(e,t,n,r,s=1){if(null==e)return e;let a;return a="same"===n?e:e-(t+(t-1)*(s-1))+1,Math.floor((a+r-1)/r)}function lk(e,t,n,r){if(null==e)return null;if("valid"===r)e=e*t+bb([n-t,0]);else{if("same"!==r)throw new $y(`Unsupport padding mode: ${r}.`);e*=t}return e}function ck(e,t){return wi((()=>(ob(t),"channelsFirst"===t?Ju(e,[0,2,3,1]):e)))}function hk(e,t){return wi((()=>(ob(t),"channelsFirst"===t?Ju(e,[0,2,3,4,1]):e)))}function pk(e,t,n,r=[1,1],s="valid",a,i,o=null){return wi((()=>{if(null==a&&(a="channelsLast"),ob(a),3!==e.rank&&4!==e.rank)throw new $y(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new $y(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let u=ck(e,a);if("causal"===s)throw new Ey("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return u=Yd({x:u,filter:t,strides:r,pad:"same"===s?"same":"valid",dilations:i,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===a&&(u=Ju(u,[0,3,1,2])),u}))}ik.className="Softmax",iu(ik);class dk extends kx{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",dk.verifyArgs(t),this.rank=e,Ky(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new Ey(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=ok(t.kernelSize,e,"kernelSize"),this.strides=ok(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,ub(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,ob(this.dataFormat),this.activation=qv(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=ix(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Ux(t.biasConstraint),this.biasRegularizer=ek(t.biasRegularizer),this.activityRegularizer=ek(t.activityRegularizer),this.dilationRate=ok(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new $y(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(2===this.rank){if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate];else if(2!==this.dilationRate.length)throw new $y(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(3===this.rank)if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(3!==this.dilationRate.length)throw new $y(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(Fy("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!=typeof e.kernelSize&&!qy(e.kernelSize,"number",1,3))throw new $y(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:jv(this.activation),useBias:this.useBias,biasInitializer:ax(this.biasInitializer),biasRegularizer:Zv(this.biasRegularizer),activityRegularizer:Zv(this.activityRegularizer),biasConstraint:Bx(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class fk extends dk{constructor(e,t){super(e,t),this.kernel=null,fk.verifyArgs(t),this.filters=t.filters,Ky(this.filters,"filters"),this.kernelInitializer=ix(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Ux(t.kernelConstraint),this.kernelRegularizer=ek(t.kernelRegularizer)}build(e){e=cx(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new $y(`The channel dimension of the input should be defined. Found ${e[t]}`);const n=e[t],r=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",r,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return wi((()=>{let t;e=lx(e);const n=null==this.bias?null:this.bias.read(),r=Yy(this.activation.getClassName());if(null!=r&&2===this.rank)t=pk(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(1===this.rank)t=function(e,t,n,r=1,s="valid",a,i=1){return wi((()=>{if(null==a&&(a="channelsLast"),ob(a),3!==e.shape.length)throw new $y(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new $y(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new $y(`The bias for a conv1dWithBias operation should be 1, but is ${n.shape.length} instead`);if("channelsFirst"===a&&(e=Ju(e,[0,2,1])),"causal"===s)throw new Ey("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=jc(e,t,r,"same"===s?"same":"valid","NWC",i);return null!=n&&(o=Db(o,n)),o}))}(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=pk(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new Ey("convolutions greater than 3D are not implemented yet.");t=function(e,t,n,r=[1,1,1],s="valid",a,i){return wi((()=>{if(null==a&&(a="channelsLast"),ob(a),4!==e.rank&&5!==e.rank)throw new $y(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new $y(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=hk(e,a);if("causal"===s)throw new Ey("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=Kc(o,t,r,"same"===s?"same":"valid","NDHWC",i),null!=n&&(o=Db(o,n)),"channelsFirst"===a&&(o=Ju(o,[0,4,1,2,3])),o}))}(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate)}null!=this.activation&&(t=this.activation.apply(t))}return t}))}computeOutputShape(e){e=cx(e);const t=[],n="channelsLast"===this.dataFormat?e.slice(1,e.length-1):e.slice(2);for(let e=0;e<n.length;++e){const r=uk(n[e],this.kernelSize[e],this.padding,this.strides[e],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[e]);t.push(r)}let r=[e[0]];return"channelsLast"===this.dataFormat?(r=r.concat(t),r.push(this.filters)):(r.push(this.filters),r=r.concat(t)),r}getConfig(){const e={filters:this.filters,kernelInitializer:ax(this.kernelInitializer),kernelRegularizer:Zv(this.kernelRegularizer),kernelConstraint:Bx(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||"number"!=typeof e.filters||e.filters<1)throw new $y(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class mk extends fk{constructor(e){super(2,e),mk.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!qy(e.kernelSize,"number",1,2))throw new $y(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}mk.className="Conv2D",iu(mk);class gk extends fk{constructor(e){super(3,e),gk.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&(!Array.isArray(e.kernelSize)||1!==e.kernelSize.length&&3!==e.kernelSize.length))throw new $y(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}gk.className="Conv3D",iu(gk);class yk extends mk{constructor(e){if(super(e),this.inputSpec=[new yx({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new $y(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=cx(e)).length)throw new $y("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new $y("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],r=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",r,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new yx({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return wi((()=>{let t=lx(e);if(4!==t.shape.length)throw new $y(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,r=n[0];let s,a;"channelsFirst"===this.dataFormat?(s=2,a=3):(s=1,a=2);const i=n[s],o=n[a],u=this.kernelSize[0],l=this.kernelSize[1],c=this.strides[0],h=this.strides[1],p=[r,lk(i,c,u,this.padding),lk(o,h,l,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=Ju(t,[0,2,3,1]));let d=qc(t,this.kernel.read(),p,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(d=Ju(d,[0,3,1,2])),null!=this.bias&&(d=Db(d,this.bias.read(),this.dataFormat)),null!=this.activation&&(d=this.activation.apply(d)),d}))}computeOutputShape(e){const t=(e=cx(e)).slice();let n,r,s;"channelsFirst"===this.dataFormat?(n=1,r=2,s=3):(n=3,r=1,s=2);const a=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],u=this.strides[1];return t[n]=this.filters,t[r]=lk(t[r],o,a,this.padding),t[s]=lk(t[s],u,i,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}yk.className="Conv2DTranspose",iu(yk);class bk extends gk{constructor(e){if(super(e),this.inputSpec=[new yx({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new $y(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(5!==(e=cx(e)).length)throw new $y("Input should have rank 5; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new $y("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],r=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",r,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new yx({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return wi((()=>{let t=lx(e);if(5!==t.shape.length)throw new $y(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,r=n[0];let s,a,i;"channelsFirst"===this.dataFormat?(i=2,s=3,a=4):(i=1,s=2,a=3);const o=n[i],u=n[s],l=n[a],c=this.kernelSize[0],h=this.kernelSize[1],p=this.kernelSize[2],d=this.strides[0],f=this.strides[1],m=this.strides[2],g=[r,lk(o,d,c,this.padding),lk(u,f,h,this.padding),lk(l,m,p,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=Ju(t,[0,2,3,4,1]));let y=Yc(t,this.kernel.read(),g,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(y=Ju(y,[0,4,1,2,3])),null!==this.bias&&(y=Db(y,this.bias.read(),this.dataFormat)),null!==this.activation&&(y=this.activation.apply(y)),y}))}computeOutputShape(e){const t=(e=cx(e)).slice();let n,r,s,a;"channelsFirst"===this.dataFormat?(n=1,r=2,s=3,a=4):(n=4,r=1,s=2,a=3);const i=this.kernelSize[0],o=this.kernelSize[1],u=this.kernelSize[2],l=this.strides[0],c=this.strides[1],h=this.strides[2];return t[n]=this.filters,t[r]=lk(t[r],l,i,this.padding),t[s]=lk(t[s],c,o,this.padding),t[a]=lk(t[a],h,u,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}bk.className="Conv3DTranspose",iu(bk);class xk extends fk{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,null==t.filters)throw new $y("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new $y("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=t.padding&&"same"!==t.padding&&"valid"!==t.padding)throw new $y(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,this.depthwiseInitializer=ix(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=ek(t.depthwiseRegularizer),this.depthwiseConstraint=Ux(t.depthwiseConstraint),this.pointwiseInitializer=ix(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=ek(t.pointwiseRegularizer),this.pointwiseConstraint=Ux(t.pointwiseConstraint)}build(e){if((e=cx(e)).length<this.rank+2)throw new $y(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t]||e[t]<0)throw new $y(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);const n=e[t],r=this.kernelSize.concat([n,this.depthMultiplier]),s=[];for(let e=0;e<this.rank;++e)s.push(1);s.push(n*this.depthMultiplier,this.filters);const a=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",r,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,a,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",s,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,a,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,a,this.biasConstraint):this.bias=null,this.inputSpec=[new yx({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return wi((()=>{let t;if(e=lx(e),1===this.rank)throw new Ey("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=Ju(e,[0,2,3,1])),t=ed(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=Db(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=Ju(t,[0,3,1,2])),t}))}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=ax(this.depthwiseInitializer),e.pointwiseInitializer=ax(this.pointwiseInitializer),e.depthwiseRegularizer=Zv(this.depthwiseRegularizer),e.pointwiseRegularizer=Zv(this.pointwiseRegularizer),e.depthwiseConstraint=Bx(this.depthwiseConstraint),e.pointwiseConstraint=Bx(this.pointwiseConstraint),e}}xk.className="SeparableConv";class wk extends xk{constructor(e){super(2,e)}}wk.className="SeparableConv2D",iu(wk);class vk extends fk{constructor(e){super(1,e),vk.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!qy(e.kernelSize,"number",1,1))throw new $y(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}vk.className="Conv1D",iu(vk);class kk extends kx{constructor(e){super(e),"number"==typeof e.cropping?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return"channelsFirst"===this.dataFormat?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return wi((()=>{if(e=lx(e),"channelsLast"===this.dataFormat){const t=Tb(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Tb(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=Tb(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Tb(t,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}}))}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}kk.className="Cropping2D",iu(kk);class Ik extends kx{constructor(e){var t;super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=null==e.size?this.DEFAULT_SIZE:e.size,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,ob(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,Hy(nb,"InterpolationFormat",t)}computeOutputShape(e){if("channelsFirst"===this.dataFormat){const t=null==e[2]?null:this.size[0]*e[2],n=null==e[3]?null:this.size[1]*e[3];return[e[0],e[1],t,n]}{const t=null==e[1]?null:this.size[0]*e[1],n=null==e[2]?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return wi((()=>{let t=lx(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=Ju(t,[0,2,3,1]);const e=this.size[0]*n[2],r=this.size[1]*n[3],s="nearest"===this.interpolation?Zf.resizeNearestNeighbor(t,[e,r]):Zf.resizeBilinear(t,[e,r]);return Ju(s,[0,3,1,2])}{const e=this.size[0]*n[1],r=this.size[1]*n[2];return"nearest"===this.interpolation?Zf.resizeNearestNeighbor(t,[e,r]):Zf.resizeBilinear(t,[e,r])}}))}getConfig(){const e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}}Ik.className="UpSampling2D",iu(Ik);class Nk extends dk{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=ix(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Ux(e.depthwiseConstraint),this.depthwiseRegularizer=ek(e.depthwiseRegularizer)}build(e){if((e=cx(e)).length<4)throw new $y(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t="channelsFirst"===this.dataFormat?1:3;if(null==e[t]||e[t]<0)throw new $y(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const n=e[t],r=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",r,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return wi((()=>{let t=function(e,t,n=[1,1],r="valid",s,a){return wi((()=>{null==s&&(s="channelsLast"),ob(s);let i=ck(e,s);if(4!==e.rank)throw new $y(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(4!==t.rank)throw new $y(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=rh(i,t,n,"same"===r?"same":"valid","NHWC",a),"channelsFirst"===s&&(i=Ju(i,[0,3,1,2])),i}))}(e=lx(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(t=Db(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),t}))}computeOutputShape(e){e=cx(e);const t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],r="channelsFirst"===this.dataFormat?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,s=uk(t,this.kernelSize[0],this.padding,this.strides[0]),a=uk(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[e[0],r,s,a]:[e[0],s,a,r]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=ax(this.depthwiseInitializer),e.depthwiseRegularizer=Zv(this.depthwiseRegularizer),e.depthwiseConstraint=Bx(this.depthwiseRegularizer),e}}Nk.className="DepthwiseConv2D",iu(Nk);var Sk=n(96763);function Tk(e,t,n,r){if(Array.isArray(e)){if(null!=t||null!=n)throw new $y("When inputs is an array, neither initialState or constants should be provided");null!=r&&(n=e.slice(e.length-r,e.length),e=e.slice(0,e.length-r)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function s(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=s(t),constants:n=s(n)}}function Ck(e,t,n,r=!1,s,a,i=!1,o=!1){return wi((()=>{const u=t.shape.length;if(u<3)throw new $y(`Input should be at least 3D, but is ${u}D.`);const l=[1,0].concat(xb(2,u));if(t=Ju(t,l),null!=a)throw new Ey("The rnn() functoin of the deeplearn.js backend does not support constants yet.");i&&Sk.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=s&&((s=Lo(Lo(s,"bool"),"float32")).rank===u-1&&(s=Eh(s,-1)),s=Ju(s,l)),r&&(t=Hp(t,0),null!=s&&(s=Hp(s,0)));const c=[];let h,p=n;const d=t.shape[0],f=Rd(t);let m,g;null!=s&&(m=Rd(s));for(let t=0;t<d;++t){const n=f[t],r=wi((()=>e(n,p)));if(null==s)h=r[0],p=r[1];else{const e=wi((()=>{const e=m[t],n=du(bp(e),e);return{output:Wo(Go(r[0],e),Go(p[0],n)),newStates:p.map(((t,s)=>Wo(Go(r[1][s],e),Go(t,n))))}}));h=e.output,p=e.newStates}o&&c.push(h)}return o&&(g=yd(c,1)),[h,g,p]}))}class $k extends kx{constructor(e){let t;if(super(e),null==e.cell)throw new $y("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new Mk({cells:e.cell}):e.cell,null==t.stateSize)throw new $y("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=null!=e.returnSequences&&e.returnSequences,this.returnState=null!=e.returnState&&e.returnState,this.goBackwards=null!=e.goBackwards&&e.goBackwards,this._stateful=null!=e.stateful&&e.stateful,this.unroll=null!=e.unroll&&e.unroll,this.supportsMasking=!0,this.inputSpec=[new yx({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){return null==this.states_?xb(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((e=>null)):this.states_}setStates(e){this.states_=e}computeOutputShape(e){ox(e)&&(e=e[0]);let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const n=t[0];let r;if(r=this.returnSequences?[e[0],e[1],n]:[e[0],n],this.returnState){const n=[];for(const r of t)n.push([e[0],r]);return[r].concat(n)}return r}computeMask(e,t){return wi((()=>{Array.isArray(t)&&(t=t[0]);const e=this.returnSequences?t:null;if(this.returnState){const t=this.states.map((e=>null));return[e].concat(t)}return e}))}get states(){if(null==this.states_){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}return this.states_}set states(e){this.states_=e}build(e){if(null!=this.numConstants)throw new Ey("Constants support is not implemented in RNN yet.");ox(e)&&(e=e[0]);const t=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new yx({shape:[t,null,...n]});const r=[e[0]].concat(e.slice(2));let s;if(this.cell.build(r),s=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!pe(this.stateSpec.map((e=>e.shape[e.shape.length-1])),s))throw new $y(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=s.map((e=>new yx({shape:[null,e]})));this.stateful&&this.resetStates()}resetStates(e,t=!1){wi((()=>{if(!this.stateful)throw new Ty("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new $y("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.states_)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>up([n,e]))):this.states_=[up([n,this.cell.stateSize])];else if(null==e)vi(this.states_),null!=this.keptStates&&(vi(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>up([n,e]))):this.states_[0]=up([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new $y(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);!0===t?this.keptStates.push(this.states_.slice()):vi(this.states_);for(let t=0;t<this.states_.length;++t){const r=e[t],s=Array.isArray(this.cell.stateSize)?this.cell.stateSize[t]:this.cell.stateSize,a=[n,s];if(!pe(r.shape,a))throw new $y(`State ${t} is incompatible with layer ${this.name}: expected shape=${a}, received shape=${r.shape}`);this.states_[t]=r}}this.states_=this.states_.map((e=>ki(e.clone())))}))}apply(e,t){let n=null==t?null:t.initialState,r=null==t?null:t.constants;null==t&&(t={});const s=Tk(e,n,r,this.numConstants);e=s.inputs,n=s.initialState,r=s.constants;let a=[],i=[];if(null!=n){t.initialState=n,a=a.concat(n),this.stateSpec=[];for(const e of n)this.stateSpec.push(new yx({shape:e.shape}));i=i.concat(this.stateSpec)}if(null!=r&&(t.constants=r,a=a.concat(r),this.numConstants=r.length),a[0]instanceof bx){const n=[e].concat(a),r=this.inputSpec.concat(i),s=this.inputSpec;this.inputSpec=r;const o=super.apply(n,t);return this.inputSpec=s,o}return super.apply(e,t)}call(e,t){return wi((()=>{const n=null==t?null:t.mask,r=null==t?null:t.training;let s=null==t?null:t.initialState;e=lx(e),null==s&&(s=this.stateful?this.states_:this.getInitialState(e));const a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(s.length!==a)throw new $y(`RNN Layer has ${a} state(s) but was passed ${s.length} initial state(s).`);this.unroll&&Sk.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const i={training:r},o=Ck(((e,t)=>{const n=this.cell.call([e].concat(t),i);return[n[0],n.slice(1)]}),e,s,this.goBackwards,n,null,this.unroll,this.returnSequences),u=o[0],l=o[1],c=o[2];this.stateful&&this.resetStates(c,r);const h=this.returnSequences?l:u;return this.returnState?[h].concat(c):h}))}getInitialState(e){return wi((()=>{let t=up(e.shape);return t=Nh(t,[1,2]),t=Ib(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((e=>e>1?Eb(t,[1,e]):t)):this.cell.stateSize>1?[Eb(t,[1,this.cell.stateSize])]:[t]}))}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);const n=this.cell.getConfig();return this.getClassName()===$k.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign(Object.assign(Object.assign({},n),e),t)}static fromConfig(e,t,n={}){const r=xw(t.cell,n);return new e(Object.assign(t,{cell:r}))}}$k.className="RNN",iu($k);class Ek extends kx{}class Ak extends Ek{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Ky(this.units,"units"),this.activation=qv(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=ix(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=ix(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=ix(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=ek(e.kernelRegularizer),this.recurrentRegularizer=ek(e.recurrentRegularizer),this.biasRegularizer=ek(e.biasRegularizer),this.kernelConstraint=Ux(e.kernelConstraint),this.recurrentConstraint=Ux(e.recurrentConstraint),this.biasConstraint=Ux(e.biasConstraint),this.dropout=yb([1,bb([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=yb([1,bb([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=cx(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return wi((()=>{if(2!==e.length)throw new $y(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];const r=null!=t.training&&t.training;let s;0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Lk({ones:()=>bp(e),rate:this.dropout,training:r,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Lk({ones:()=>bp(n),rate:this.recurrentDropout,training:r,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,i=this.recurrentDropoutMask;s=Rb(null!=a?Go(e,a):e,this.kernel.read()),null!=this.bias&&(s=Db(s,this.bias.read())),null!=i&&(n=Go(n,i));let o=Wo(s,Rb(n,this.recurrentKernel.read()));return null!=this.activation&&(o=this.activation.apply(o)),[o,o]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:jv(this.activation),useBias:this.useBias,kernelInitializer:ax(this.kernelInitializer),recurrentInitializer:ax(this.recurrentInitializer),biasInitializer:ax(this.biasInitializer),kernelRegularizer:Zv(this.kernelRegularizer),recurrentRegularizer:Zv(this.recurrentRegularizer),biasRegularizer:Zv(this.biasRegularizer),activityRegularizer:Zv(this.activityRegularizer),kernelConstraint:Bx(this.kernelConstraint),recurrentConstraint:Bx(this.recurrentConstraint),biasConstraint:Bx(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}Ak.className="SimpleRNNCell",iu(Ak);class Rk extends $k{constructor(e){e.cell=new Ak(e),super(e)}call(e,t){return wi((()=>{null!=this.cell.dropoutMask&&(vi(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(vi(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,r=null==t?null:t.training,s=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})}))}static fromConfig(e,t){return new e(t)}}Rk.className="SimpleRNN",iu(Rk);class Ok extends Ek{constructor(e){if(super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new $y("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Ky(this.units,"units"),this.activation=qv(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=qv(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=ix(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=ix(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=ix(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=ek(e.kernelRegularizer),this.recurrentRegularizer=ek(e.recurrentRegularizer),this.biasRegularizer=ek(e.biasRegularizer),this.kernelConstraint=Ux(e.kernelConstraint),this.recurrentConstraint=Ux(e.recurrentConstraint),this.biasConstraint=Ux(e.biasConstraint),this.dropout=yb([1,bb([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=yb([1,bb([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){const t=(e=cx(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return wi((()=>{if(2!==e.length)throw new $y(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const n=null!=t.training&&t.training;let r=e[1];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Lk({ones:()=>bp(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Lk({ones:()=>bp(r),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,a=this.recurrentDropoutMask;let i,o,u;0<this.dropout&&this.dropout<1&&(e=Go(e,s[0]));let l=Rb(e,this.kernel.read());this.useBias&&(l=Db(l,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(r=Go(r,a[0]));const c=this.recurrentKernel.read(),[h,p]=dd(c,[2*this.units,this.units],c.rank-1),d=Rb(r,h),[f,m,g]=dd(l,3,l.rank-1),[y,b]=dd(d,2,d.rank-1);i=this.recurrentActivation.apply(Wo(f,y)),o=this.recurrentActivation.apply(Wo(m,b));const x=Rb(Go(o,r),p);u=this.activation.apply(Wo(g,x));const w=Wo(Go(i,r),Go(Wo(1,Xu(i)),u));return[w,w]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:jv(this.activation),recurrentActivation:jv(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ax(this.kernelInitializer),recurrentInitializer:ax(this.recurrentInitializer),biasInitializer:ax(this.biasInitializer),kernelRegularizer:Zv(this.kernelRegularizer),recurrentRegularizer:Zv(this.recurrentRegularizer),biasRegularizer:Zv(this.biasRegularizer),activityRegularizer:Zv(this.activityRegularizer),kernelConstraint:Bx(this.kernelConstraint),recurrentConstraint:Bx(this.recurrentConstraint),biasConstraint:Bx(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}}Ok.className="GRUCell",iu(Ok);class Fk extends $k{constructor(e){0===e.implementation&&Sk.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Ok(e),super(e)}call(e,t){return wi((()=>{null!=this.cell.dropoutMask&&(vi(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(vi(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,r=null==t?null:t.training,s=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Fk.className="GRU",iu(Fk);class _k extends Ek{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Ky(this.units,"units"),this.activation=qv(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=qv(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=ix(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=ix(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=ix(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=ek(e.kernelRegularizer),this.recurrentRegularizer=ek(e.recurrentRegularizer),this.biasRegularizer=ek(e.biasRegularizer),this.kernelConstraint=Ux(e.kernelConstraint),this.recurrentConstraint=Ux(e.recurrentConstraint),this.biasConstraint=Ux(e.biasConstraint),this.dropout=yb([1,bb([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=yb([1,bb([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;const n=(e=cx(e))[e.length-1];let r;if(this.kernel=this.addWeight("kernel",[n,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){const e=this.biasInitializer,n=this.units;r=new((t=class extends Wb{apply(t,r){const s=e.apply([n]),a=(new Vb).apply([n]),i=e.apply([2*n]);return $b($b(s,a),i)}}).className="CustomInit",t)}else r=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,r,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return wi((()=>{const n=null!=t.training&&t.training;if(3!==e.length)throw new $y(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let r=e[1];const s=e[2];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Lk({ones:()=>bp(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Lk({ones:()=>bp(r),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,i=this.recurrentDropoutMask;let o,u,l,c;0<this.dropout&&this.dropout<1&&(e=Go(e,a[0]));let h=Rb(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(r=Go(r,i[0])),h=Wo(h,Rb(r,this.recurrentKernel.read())),this.useBias&&(h=Db(h,this.bias.read()));const[p,d,f,m]=dd(h,4,h.rank-1);o=this.recurrentActivation.apply(p),u=this.recurrentActivation.apply(d),l=Wo(Go(u,s),Go(o,this.activation.apply(f))),c=this.recurrentActivation.apply(m);const g=Go(c,this.activation.apply(l));return[g,g,l]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:jv(this.activation),recurrentActivation:jv(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ax(this.kernelInitializer),recurrentInitializer:ax(this.recurrentInitializer),biasInitializer:ax(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Zv(this.kernelRegularizer),recurrentRegularizer:Zv(this.recurrentRegularizer),biasRegularizer:Zv(this.biasRegularizer),activityRegularizer:Zv(this.activityRegularizer),kernelConstraint:Bx(this.kernelConstraint),recurrentConstraint:Bx(this.recurrentConstraint),biasConstraint:Bx(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}}_k.className="LSTMCell",iu(_k);class Dk extends $k{constructor(e){0===e.implementation&&Sk.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new _k(e),super(e)}call(e,t){return wi((()=>{null!=this.cell.dropoutMask&&(vi(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(vi(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,r=null==t?null:t.training,s=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Dk.className="LSTM",iu(Dk);class Mk extends Ek{constructor(e){super(e),this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return wi((()=>{let n=e.slice(1);const r=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?r.push(n.splice(0,e.stateSize.length)):r.push(n.splice(0,1));r.reverse();const s=[];let a;for(let i=0;i<this.cells.length;++i){const o=this.cells[i];n=r[i],a=0===i?[e[0]].concat(n):[a[0]].concat(n),a=o.call(a,t),s.push(a.slice(1))}n=[];for(const e of s.slice().reverse())n.push(...e);return[a[0]].concat(n)}))}build(e){let t;ox(e)&&(e=e[0]),this.cells.forEach(((n,r)=>{hb(`RNNCell_${r}`,(()=>{n.build(e),t=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,e=[e[0],t]}))})),this.built=!0}getConfig(){const e=super.getConfig(),t={cells:this.cells.map((e=>({className:e.getClassName(),config:e.getConfig()})))};return Object.assign(Object.assign({},e),t)}static fromConfig(e,t,n={}){const r=[];for(const e of t.cells)r.push(xw(e,n));return new e({cells:r})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.cells)t.push(...e.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return fx(e)}setWeights(e){const t=[];for(const n of this.cells){const r=n.weights.length,s=e.splice(r);for(let e=0;e<n.weights.length;++e)t.push([n.weights[e],s[e]])}mx(t)}}function Lk(e){const{ones:t,rate:n,training:r=!1,count:s=1,dropoutFunc:a}=e,i=()=>null!=a?a(t(),n):Mb(t(),n),o=()=>Lb(i,t,r);return!s||s<=1?ki(o().clone()):Array(s).fill(void 0).map(o).map((e=>ki(e.clone())))}Mk.className="StackedRNNCells",iu(Mk);class zk extends $k{constructor(e){if(e.unroll)throw new Ey("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Ey("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new yx({ndim:5})]}call(e,t){return wi((()=>{if(null!=this.cell.dropoutMask&&(vi(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(vi(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new $y("ConvRNN2D cell does not support constants");const n=null==t?null:t.mask,r=null==t?null:t.training,s=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})}))}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return wi((()=>{const{stateSize:t}=this.cell,n=e.shape,r=this.computeSingleOutputShape(n),s=up([r[0],...r.slice(2)]);return Array.isArray(t)?Array(t.length).fill(s):[s]}))}resetStates(e,t=!1){wi((()=>{if(!this.stateful)throw new Ty("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape,r=this.computeSingleOutputShape(n),s=[r[0],...r.slice(2)];if(null==n[0])throw new $y("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.getStates())Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>up(s))):this.states_=[up(s)];else if(null==e)vi(this.states_),null!=this.keptStates&&(vi(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>up(s))):this.states_[0]=up(s);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new $y(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):vi(this.states_);for(let t=0;t<this.states_.length;++t){const n=e[t],r=s;if(!pe(n.shape,r))throw new $y(`State ${t} is incompatible with layer ${this.name}: expected shape=${r}, received shape=${n.shape}`);this.states_[t]=n}}this.states_=this.states_.map((e=>ki(e.clone())))}))}computeSingleOutputShape(e){const{dataFormat:t,filters:n,kernelSize:r,padding:s,strides:a,dilationRate:i}=this.cell,o="channelsFirst"===t,u=e[o?3:2],l=e[o?4:3],c=uk(u,r[0],s,a[0],i[0]),h=uk(l,r[1],s,a[1],i[1]);return[...e.slice(0,2),...o?[n,c,h]:[c,h,n]]}}zk.className="ConvRNN2D";class Pk extends _k{constructor(e){const{filters:t,kernelSize:n,strides:r,padding:s,dataFormat:a,dilationRate:i}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,Ky(this.filters,"filters"),this.kernelSize=ok(n,2,"kernelSize"),this.kernelSize.forEach((e=>Ky(e,"kernelSize"))),this.strides=ok(r||1,2,"strides"),this.strides.forEach((e=>Ky(e,"strides"))),this.padding=s||"valid",ub(this.padding),this.dataFormat=a||"channelsLast",ob(this.dataFormat),this.dilationRate=ok(i||1,2,"dilationRate"),this.dilationRate.forEach((e=>Ky(e,"dilationRate")))}build(e){var t;e=cx(e);const n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new $y(`The channel dimension of the input should be defined. Found ${e[n]}`);const r=e[n],s=this.kernelSize.concat([r,4*this.filters]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const a=this.kernelSize.concat([this.filters,4*this.filters]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",a,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let e;if(this.unitForgetBias){const n=this.biasInitializer,r=this.filters;e=new((t=class extends Wb{apply(e,t){return Cb([n.apply([r]),lp([r]),n.apply([2*r])])}}).className="CustomInit",t)}else e=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.filters],null,e,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return wi((()=>{if(3!==e.length)throw new $y(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training||!1,r=e[0],s=e[1],a=e[2];0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Lk({ones:()=>bp(r),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const i=this.dropoutMask,o=(e,t,n)=>t&&t[n]?Go(t[n],e):e;let u=o(r,i,0),l=o(r,i,1),c=o(r,i,2),h=o(r,i,3);0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Lk({ones:()=>bp(s),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const p=this.recurrentDropoutMask;let d=o(s,p,0),f=o(s,p,1),m=o(s,p,2),g=o(s,p,3);const[y,b,x,w]=dd(this.kernel.read(),4,3),[v,k,I,N]=this.useBias?dd(this.bias.read(),4):[null,null,null,null];u=this.inputConv(u,y,v,this.padding),l=this.inputConv(l,b,k,this.padding),c=this.inputConv(c,x,I,this.padding),h=this.inputConv(h,w,N,this.padding);const[S,T,C,$]=dd(this.recurrentKernel.read(),4,3);d=this.recurrentConv(d,S),f=this.recurrentConv(f,T),m=this.recurrentConv(m,C),g=this.recurrentConv(g,$);const E=this.recurrentActivation.apply(Wo(u,d)),A=this.recurrentActivation.apply(Wo(l,f)),R=Wo(Go(A,a),Go(E,this.activation.apply(Wo(c,m)))),O=Go(this.recurrentActivation.apply(Wo(h,g)),this.activation.apply(R));return[O,O,R]}))}getConfig(){const e=super.getConfig(),{units:t}=e,n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]])}return n}(e,["units"]),r={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},n),r)}inputConv(e,t,n,r){const s=Gc(e,t,this.strides,r||"valid","channelsFirst"===this.dataFormat?"NCHW":"NHWC",this.dilationRate);return n?Db(s,n,this.dataFormat):s}recurrentConv(e,t){return Gc(e,t,1,"same","channelsFirst"===this.dataFormat?"NCHW":"NHWC")}}Pk.className="ConvLSTM2DCell",iu(Pk);class Bk extends zk{constructor(e){const t=new Pk(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}}Bk.className="ConvLSTM2D",iu(Bk);class Wk extends kx{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(null==this.noiseShape)return this.noiseShape;const t=e.shape,n=[];for(let e=0;e<this.noiseShape.length;++e)n.push(null==this.noiseShape[e]?t[e]:this.noiseShape[e]);return n}call(e,t){return wi((()=>{this.invokeCallHook(e,t);const n=lx(e);if(0<this.rate&&this.rate<1){const e=null!=t.training&&t.training,r=this.getNoiseShape(n);return Lb((()=>Mb(n,this.rate,r,this.seed)),(()=>n),e)}return e}))}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}Wk.className="Dropout",iu(Wk);class Uk extends Wk{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}Uk.className="SpatialDropout1D",iu(Uk);class Vk extends kx{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){let t=null;null!=e.batchSize&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,Ky(this.units,"units"),this.activation=qv(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=ix(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=ix(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Ux(e.kernelConstraint),this.biasConstraint=Ux(e.biasConstraint),this.kernelRegularizer=ek(e.kernelRegularizer),this.biasRegularizer=ek(e.biasRegularizer),this.activityRegularizer=ek(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=cx(e))[e.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){const t=(e=cx(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return wi((()=>{this.invokeCallHook(e,t);const n=lx(e),r=Yy(this.activation.getClassName());let s;return null!=r?s=Rb(n,this.kernel.read(),r,this.bias?this.bias.read():null):(s=Rb(n,this.kernel.read()),null!=this.bias&&(s=Db(s,this.bias.read())),null!=this.activation&&(s=this.activation.apply(s))),s}))}getConfig(){const e={units:this.units,activation:jv(this.activation),useBias:this.useBias,kernelInitializer:ax(this.kernelInitializer),biasInitializer:ax(this.biasInitializer),kernelRegularizer:Zv(this.kernelRegularizer),biasRegularizer:Zv(this.biasRegularizer),activityRegularizer:Zv(this.activityRegularizer),kernelConstraint:Bx(this.kernelConstraint),biasConstraint:Bx(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}Vk.className="Dense",iu(Vk);class Gk extends kx{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=cx(e);for(const t of e.slice(1))if(null==t)throw new $y(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],gb(e,1)]}call(e,t){return wi((()=>{this.invokeCallHook(e,t);let n=lx(e);if("channelsFirst"===this.dataFormat&&n.rank>1){const e=[0];for(let t=2;t<n.rank;++t)e.push(t);e.push(1),n=Ju(n,e)}return function(e){if(e.rank<=1)throw new $y(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],gb(e.shape,1)];return vc(e,t)}(n)}))}getConfig(){const e={};null!=this.dataFormat&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}Gk.className="Flatten",iu(Gk);class jk extends kx{constructor(e){super(e),this.supportsMasking=!0,this.activation=qv(e.activation)}call(e,t){return wi((()=>{this.invokeCallHook(e,t);const n=lx(e);return this.activation.apply(n)}))}getConfig(){const e={activation:jv(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}jk.className="Activation",iu(jk);class Hk extends kx{constructor(e){super(e),this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return wi((()=>{return e=lx(e),t=e,n=this.n,wi((()=>{if(2!==t.shape.length)throw new $y(`repeat() expects a rank-2 tensor, but received a rank-${t.shape.length} tensor.`);return Eb(Ib(t,1),[1,n,1])}));var t,n}))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}Hk.className="RepeatVector",iu(Hk);class qk extends kx{constructor(e){super(e),this.targetShape=e.targetShape;for(let e=0;e<this.targetShape.length;++e)this.isUnknown(this.targetShape[e])&&(this.targetShape[e]=null)}isUnknown(e){return e<0||null==e}fixUnknownDimension(e,t){const n="Total size of new array must be unchanged.",r=t.slice();let s=1,a=null;for(let e=0;e<r.length;++e){const t=r[e];if(this.isUnknown(t)){if(null!==a)throw new $y("Can only specifiy one unknown dimension.");a=e}else s*=t}const i=gb(e);if(null!==a){if(0===s||i%s!=0)throw new $y(n);r[a]=i/s}else if(i!==s)throw new $y(n);return r}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return wi((()=>{this.invokeCallHook(e,t);const n=lx(e),r=n.shape,s=r.slice(0,1).concat(this.fixUnknownDimension(r.slice(1),this.targetShape));return vc(n,s)}))}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}qk.className="Reshape",iu(qk);class Kk extends kx{constructor(e){if(super(e),null==e.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);const t=xb(1,e.dims.length+1);if(!pe(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new yx({ndim:this.dims.length+1})]}computeOutputShape(e){const t=(e=cx(e)).slice();return this.dims.forEach(((n,r)=>{t[r+1]=e[n]})),t}call(e,t){return Ju(lx(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}Kk.className="Permute",iu(Kk);class Xk extends kx{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,this.maskValue=null!=e?null==e.maskValue?0:e.maskValue:0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const n=lx(e);return Zl(yp(n,this.maskValue),-1)}call(e,t){return wi((()=>{this.invokeCallHook(e,t);const n=lx(e),r=Zl(yp(n,this.maskValue),-1,!0);return Go(n,Lo(r,n.dtype))}))}}Xk.className="Masking",iu(Xk);class Yk extends kx{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==e.batchInputShape&&null==e.inputShape){let t=null;null!=e.batchSize&&(t=e.batchSize),null==e.inputLength?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(My(e.inputLength))}this.inputDim=e.inputDim,Ky(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Ky(this.outputDim,"outputDim"),this.embeddingsInitializer=ix(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=ek(e.embeddingsRegularizer),this.activityRegularizer=ek(e.activityRegularizer),this.embeddingsConstraint=Ux(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return wi((()=>this.maskZero?(e=lx(e),yp(e,qo(e))):null))}computeOutputShape(e){if(e=cx(e),null==this.inputLength)return[...e,this.outputDim];const t=My(this.inputLength);if(t.length!==e.length-1)throw new $y(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let r=0;r<t.length;++r){const s=t[r],a=e[r+1];if(null!=s&&null!=a&&s!==a)throw new $y(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);null==s&&(t[n]=a),n++}}return[e[0],...t,this.outputDim]}call(e,t){return wi((()=>{this.invokeCallHook(e,t);let n=lx(e);"int32"!==n.dtype&&(n=kb(n,"int32"));const r=Ob(this.embeddings.read(),vc(n,[n.size]));return vc(r,cx(this.computeOutputShape(n.shape)))}))}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:ax(this.embeddingsInitializer),embeddingsRegularizer:Zv(this.embeddingsRegularizer),activityRegularizer:Zv(this.activityRegularizer),embeddingsConstraint:Bx(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}Yk.className="Embedding",iu(Yk);class Jk extends kx{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Ey}computeElementwiseOpOutputShape(e,t){if(null==e||null==t)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(0===t.length)return e;const n=e.slice(0,e.length-t.length);for(let r=0;r<t.length;++r){const s=e[e.length-t.length+r],a=t[r];if(null==s||null==a||s<0||a<0)n.push(null);else if(1===s)n.push(a);else if(1===a)n.push(s);else{if(s!==a)throw new $y("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(s)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[cx(e)]),e.length<2)throw new $y(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(const n of e)null!=n&&null!==n[0]&&t.push(n[0]);if(t=Gy(t),t.length>1)throw new $y(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=null==e[0]?null:e[0].slice(1);for(let t=1;t<e.length;++t){const r=null==e[t]?null:e[t].slice(1);n=this.computeElementwiseOpOutputShape(n,r)}const r=e.map((e=>e.length));-1===e.indexOf(null)&&1===Gy(r).length?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return wi((()=>{if(this.reshapeRequired){const t=[],n=e.map((e=>e.rank));if(-1===n.indexOf(null)){const r=bb(n);for(let n of e){const e=n.rank;for(let t=0;t<r-e;++t)n=Ib(n,1);t.push(n)}return this.mergeFunction(t)}{let n=!1;for(const r of e){const e=r.rank;if(null==e){const e=r.shape,s=e[0],a=e.slice(1).concat([s]);let i=vc(r,[s].concat(gb(e.slice(1))));i=Ju(i,[1,0]),i=vc(i,a),t.push(i),n=!0}else if(e>1){const s=xb(1,e).concat([0]);t.push(Ju(r,s)),n=!0}else t.push(r)}let r=this.mergeFunction(t);const s=r.rank;if(n)if(null==s){const e=r.shape,t=e[e.length-1],n=[t].concat(e.slice(0,e.length-1));r=vc(Ju(vc(r,[-1,t]),[1,0]),n)}else if(s>1){const e=[s-1].concat(xb(0,s-1));r=Ju(r,e)}return r}}return this.mergeFunction(e)}))}computeOutputShape(e){let t;t=null==e[0]?null:e[0].slice(1);for(let n=1;n<e.length;++n){const r=null==e[n]?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,r)}let n=[];for(const t of e)null!=t&&null!==t[0]&&n.push(t[0]);return n=Gy(n),t=1===n.length?n.concat(t):[null].concat(t),t}computeMask(e,t){return wi((()=>{if(null==t)return null;if(!Array.isArray(t))throw new $y("`mask` should be an Array");if(!Array.isArray(e))throw new $y("`inputs` should be an Array");if(t.length!==e.length)throw new $y(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every((e=>null==e)))return null;let n=(t=t.map((e=>null==e?e:Eh(e,0))))[0];for(let e=1;e<t.length-1;++e)n=Jh(n,t[e]);return n}))}}class Zk extends Jk{constructor(e){super(e)}mergeFunction(e){return wi((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Wo(t,e[n]);return t}))}}Zk.className="Add",iu(Zk);class Qk extends Jk{constructor(e){super(e)}mergeFunction(e){return wi((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Go(t,e[n]);return t}))}}Qk.className="Multiply",iu(Qk);class eI extends Jk{constructor(e){super(e)}mergeFunction(e){return wi((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Wo(t,e[n]);return Go(1/e.length,t)}))}}eI.className="Average",iu(eI);class tI extends Jk{constructor(e){super(e)}mergeFunction(e){return wi((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=xu(t,e[n]);return t}))}}tI.className="Maximum",iu(tI);class nI extends Jk{constructor(e){super(e)}mergeFunction(e){return wi((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=hp(t,e[n]);return t}))}}nI.className="Minimum",iu(nI);class rI extends Jk{constructor(e){super(e),this.DEFAULT_AXIS=-1,null==e&&(e={}),this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!Array.isArray(e)||!Array.isArray(e[0])||1===e.length)throw new $y("A `Concatenate` layer should be called on a list of at least 2 inputs");let t=!0;for(const n of e)if(null!=n){t=!1;break}if(t)return;const n=[];for(let t=0;t<e.length;++t){const r=e[t].slice();r.splice(this.axis,1);let s=!1;for(const e of n)if(pe(e,r)){s=!0;break}s||n.push(r)}if(n.length>1)throw new $y("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return wi((()=>Cb(e,this.axis)))}computeOutputShape(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new $y("A `Concatenate` layer should be called on a list of inputs.");const t=e,n=t[0].slice(),r=this.axis<0?n.length+this.axis:this.axis;for(const e of t.slice(1)){if(null==n[r]||null==e[r]){n[r]=null;break}n[r]+=e[r]}return n}computeMask(e,t){if(null==t)return null;if(!Array.isArray(t))throw new $y("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new $y("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new $y(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return wi((()=>{let n=!0;if(t.forEach((e=>{null==e||(n=!1)})),n)return null;const r=[];for(let n=0;n<e.length;++n)null==t[n]?r.push(Lo(bp(e[n]),"bool")):t[n].rank<e[n].rank?r.push(Eh(t[n],-1)):r.push(t[n]);const s=Nc(r,this.axis);return Jl(s,-1,!1)}))}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function sI(e,t){for(;e<0;)e+=t;return e}rI.className="Concatenate",iu(rI);class aI extends Jk{constructor(e){super(e),this.axes=e.axes,this.normalize=null!=e.normalize&&e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){ie(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),(()=>"A `Dot` layer should be called on a list of exactly 2 inputs."));const t=e[0],n=e[1];if(t.length>3||n.length>3)throw new Ey("Dot layer does not support tensors of 4D or higher rank yet.");const r=this.interpretAxes(t,n);if(t[r[0]]!==n[r[1]])throw new $y(`Dimension incompatibility: ${t[r[0]]} !== ${n[r[1]]}`)}mergeFunction(e){if(2!==e.length)throw new $y(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t,n=e[0],r=e[1];return t=Array.isArray(this.axes)?this.axes.map(((t,n)=>sI(t,e[n].shape.length))):[sI(this.axes,n.shape.length),sI(this.axes,r.shape.length)],this.normalize&&(n=ww(n,t[0]),r=ww(r,t[1])),function(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new Ey("batchDot is not implemented for tensors of 4D or higher rank yet");if(ie(e.shape.length>=2,(()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`)),ie(e.shape.length>=2,(()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`)),"number"==typeof n&&(n=[n,n]),"complex64"===e.dtype||"complex64"===t.dtype)throw new Ey("batchDot is not implemented for complex64-type Tensors yet.");const r=e.shape.length,s=t.shape.length;null==n&&(n=[r-1,s-2]);const a=n;return wi((()=>{let n,i;if(r>s){n=r-s;const e=[];for(let t=0;t<n;++t)e.push(1);t=vc(t,t.shape.concat(e))}else if(s>r){n=s-r;const t=[];for(let e=0;e<n;++e)t.push(1);e=vc(e,e.shape.concat(t))}else n=0;if(2===e.shape.length&&2===t.shape.length)i=a[0]===a[1]?Nh(Go(e,t),a[0]):Nh(Go(Ju(e,[1,0]),t),a[1]);else{const n=a[0]!==e.shape.length-1,r=a[1]===t.shape.length-1;i=Hu(e,t,n,r)}if(n>0){let e;e=r>s?r+s-3:r-1;const t=[];for(let r=e;r<e+n;++r)t.push(r);i=gd(i,t)}return 1===i.shape.length&&(i=Eh(i,1)),i}))}(n,r,t)}interpretAxes(e,t){let n;return n=Array.isArray(this.axes)?this.axes:[sI(this.axes,e.length),sI(this.axes,t.length)],n}computeOutputShape(e){ie(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),(()=>"A `Dot` layer should be called on a list of exactly 2 inputs."));const t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new Ey("Dot layer does not support tensors of 4D or higher rank yet.");const r=this.interpretAxes(t,n);t.splice(r[0],1),n.splice(r[1],1),n.splice(0,1);const s=t.concat(n);return 1===s.length&&s.push(1),s}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}aI.className="Dot",iu(aI);class iI extends kx{constructor(e){super(e),this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return wi((()=>{this.invokeCallHook(e,t);const n=lx(e);return Lb((()=>Wo(Ab(n.shape,0,this.stddev),n)),(()=>n),t.training||!1)}))}}iI.className="GaussianNoise",iu(iI);class oI extends kx{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return wi((()=>{this.invokeCallHook(e,t);const n=lx(e);return this.rate>0&&this.rate<1?Lb((()=>{const e=Math.sqrt(this.rate/(1-this.rate));return Go(n,Ab(n.shape,1,e))}),(()=>n),t.training||!1):n}))}}oI.className="GaussianDropout",iu(oI);class uI extends kx{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||lx(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return wi((()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e),r=()=>{const t=lx(e),r=-1.7580993408473766;let s=Mh(Bp(n),this.rate);s=kb(s,"float32");const a=((1-this.rate)*(1+this.rate*r**2))**-.5,i=-a*r*this.rate,o=Wo(Go(t,s),Go(Wo(s,-1),r));return Wo(Go(o,a),i)};return Lb(r,(()=>lx(e)),t.training||!1)}return e}))}}function lI(e,t,n,r,s,a=.001){let i;if(2===e.rank)i=Rc(e,t,n,r,s,a);else if(3===e.rank)i=Oc(e,t,n,r,s,a);else{if(4!==e.rank)throw new Ey(`batchNormalization is not implemented for array of rank ${e.rank} yet`);i=Fc(e,t,n,r,s,a)}return i}uI.className="AlphaDropout",iu(uI);class cI extends kx{constructor(e){null==e&&(e={}),super(e),this.supportsMasking=!0,this.axis=null==e.axis?-1:e.axis,this.momentum=null==e.momentum?.99:e.momentum,this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=ix(e.betaInitializer||"zeros"),this.gammaInitializer=ix(e.gammaInitializer||"ones"),this.movingMeanInitializer=ix(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=ix(e.movingVarianceInitializer||"ones"),this.betaConstraint=Ux(e.betaConstraint),this.gammaConstraint=Ux(e.gammaConstraint),this.betaRegularizer=ek(e.betaRegularizer),this.gammaRegularizer=ek(e.gammaRegularizer)}build(e){e=cx(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new $y(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new yx({ndim:e.length,axes:{[t]:n}})];const r=[n];this.scale&&(this.gamma=this.addWeight("gamma",r,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",r,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",r,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",r,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return wi((()=>{const n=null!=t.training&&t.training,r=lx(e),s=r.shape,a=s.length,i=xb(0,a),o=this.axis>=0?this.axis:this.axis+a;i.splice(o,1);const u=Oy(1,a);u[o]=s[o];const l=i.slice();l.sort();const c=!pe(l,xb(0,a).slice(0,a-1));if(!n)return(()=>{if(c){const e=vc(this.movingMean.read(),u),t=vc(this.movingVariance.read(),u),n=this.center?vc(this.beta.read(),u):null,s=this.scale?vc(this.gamma.read(),u):null;return lI(r,e,t,n,s,this.epsilon)}return lI(r,this.movingMean.read(),this.movingVariance.read(),null==this.beta?null:this.beta.read(),null==this.gamma?null:this.gamma.read(),this.epsilon)})();const[h,p,d]=function(e,t,n,r,s=.001){return pe(r.slice().sort(),xb(0,e.rank-1))?function(e,t,n,r,s=.001){return wi((()=>{const a=fp(e,r),i=a.mean,o=a.variance;return[lI(e,i,o,n,t,s),i,o]}))}(e,t,n,r,s):function(e,t,n,r,s=.001){return wi((()=>{const a=fp(e,r),i=a.mean,o=a.variance,u=[];for(const t of xb(0,e.rank))-1!==r.indexOf(t)?u.push(1):u.push(e.shape[t]);const l=vc(i,u),c=vc(o,u),h=null==t?null:vc(t,u),p=null==n?null:vc(n,u);return[lI(e,l,c,p,h,s),i,o]}))}(e,t,n,r,s)}(r,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(e,t,n)=>{wi((()=>{const r=1-n,s=e.read(),a=Go(du(s,t),r);e.write(du(s,a))}))};return(()=>{f(this.movingMean,p,this.momentum),f(this.movingVariance,d,this.momentum)})(),h}))}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:ax(this.betaInitializer),gammaInitializer:ax(this.gammaInitializer),movingMeanInitializer:ax(this.movingMeanInitializer),movingVarianceInitializer:ax(this.movingVarianceInitializer),betaRegularizer:Zv(this.betaRegularizer),gammaRegularizer:Zv(this.gammaRegularizer),betaConstraint:Bx(this.betaConstraint),gammaConstraint:Bx(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}cI.className="BatchNormalization",iu(cI);class hI extends kx{constructor(e){if(null==e&&(e={}),super(e),this.axis=null==e.axis?-1:e.axis,"number"==typeof this.axis){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else{if(!Array.isArray(this.axis))throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);for(const e of this.axis)if(!Number.isInteger(e))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=ix(e.betaInitializer||"zeros"),this.gammaInitializer=ix(e.gammaInitializer||"ones"),this.betaRegularizer=ek(e.betaRegularizer),this.gammaRegularizer=ek(e.gammaRegularizer),this.supportsMasking=!0}build(e){const t=(e=cx(e)).length;"number"==typeof this.axis&&(this.axis=[this.axis]);for(let e=0;e<this.axis.length;++e)this.axis[e]<0&&(this.axis[e]+=t);for(const e of this.axis)if(e<0||e>=t)throw new Error(`Invalid axis: ${e}`);if(this.axis.length!==Gy(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const n=this.axis.map((t=>e[t]));this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,!0):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,!0):this.beta=null,this.built=!0}call(e,t){const n=lx(e),r=n.shape,s=r.length;return wi((()=>{let{mean:e,variance:t}=fp(n,this.axis,!0);const a=Oy(1,s);for(const e of this.axis)a[e]=r[e];const i=e=>null!=e&&e.shape.length!==s?vc(e,a):e;let o=this.scale?i(this.gamma.read()):null,u=this.center?i(this.beta.read()):null;const l=[],c=[];for(let e=0;e<s;++e)-1!==this.axis.indexOf(e)?(l.push(r[e]),c.push(1)):(l.push(1),c.push(r[e]));return e=Rh(e,l),t=Rh(t,l),null!=o&&(o=Rh(o,c)),null!=u&&(u=Rh(u,c)),lI(n,e,t,u,o,this.epsilon)}))}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:ax(this.betaInitializer),gammaInitializer:ax(this.gammaInitializer),betaRegularizer:Zv(this.betaRegularizer),gammaRegularizer:Zv(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}hI.className="LayerNormalization",iu(hI);class pI extends kx{constructor(e){if(null==e&&(e={}),super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,null==e.padding)this.padding=[[1,1],[1,1]];else if("number"==typeof e.padding)this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,2!==e.padding.length)throw new $y(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if("number"==typeof e.padding[0])t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,2!==e.padding[0].length)throw new $y(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],2!==e.padding[1].length)throw new $y(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new yx({ndim:4})]}computeOutputShape(e){let t,n;return e=cx(e),"channelsFirst"===this.dataFormat?(t=null!=e[2]&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]])}call(e,t){return wi((()=>{return t=lx(e),n=this.padding,r=this.dataFormat,wi((()=>{if(4!==t.rank)throw new $y(`temporalPadding expects input tensor to be 4-D, but received a ${t.rank}-D tensor.`);if(null==n&&(n=[[1,1],[1,1]]),2!==n.length||2!==n[0].length||2!==n[1].length)throw new $y("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==r&&(r="channelsLast"),"channelsLast"!==r&&"channelsFirst"!==r)throw new $y(`Unknown data format: ${r}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let e;return e="channelsFirst"===r?[[0,0],[0,0],n[0],n[1]]:[[0,0],n[0],n[1],[0,0]],wp(t,e)}));var t,n,r}))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}function dI(e,t,n,r,s,a){return wi((()=>{let i;ob(s),lb(a),ub(r),null==n&&(n=[1,1]),null==r&&(r="valid"),null==s&&(s="channelsLast"),null==a&&(a="max"),e=ck(e,s);const o="same"===r?"same":"valid";return i="max"===a?sp(e,t,n,o):kc(e,t,n,o),"channelsFirst"===s&&(i=Ju(i,[0,3,1,2])),i}))}function fI(e,t,n,r,s,a){return wi((()=>{let i;ob(s),lb(a),ub(r),null==n&&(n=[1,1,1]),null==r&&(r="valid"),null==s&&(s="channelsLast"),null==a&&(a="max"),e=hk(e,s);const o="same"===r?"same":"valid";return i="max"===a?ap(e,t,n,o):Ic(e,t,n,o),"channelsFirst"===s&&(i=Ju(i,[0,4,1,2,3])),i}))}pI.className="ZeroPadding2D",iu(pI);class mI extends kx{constructor(e){if(null==e.poolSize&&(e.poolSize=2),super(e),"number"==typeof e.poolSize)this.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new $y(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);this.poolSize=e.poolSize}if(Ky(this.poolSize,"poolSize"),null==e.strides)this.strides=this.poolSize;else if("number"==typeof e.strides)this.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new $y(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);this.strides=e.strides}Ky(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,ub(this.padding),this.inputSpec=[new yx({ndim:3})]}computeOutputShape(e){const t=uk((e=cx(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return wi((()=>{this.invokeCallHook(e,t),e=Ib(lx(e),2);const n=this.poolingFunction(lx(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return gd(n,[2])}))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class gI extends mI{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return ob(s),ub(r),dI(e,t,n,r,s,"max")}}gI.className="MaxPooling1D",iu(gI);class yI extends mI{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return ob(s),ub(r),dI(e,t,n,r,s,"avg")}}yI.className="AveragePooling1D",iu(yI);class bI extends kx{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new $y(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];Ky(this.poolSize,"poolSize"),Ky(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,ob(this.dataFormat),ub(this.padding),this.inputSpec=[new yx({ndim:4})]}computeOutputShape(e){e=cx(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=uk(t,this.poolSize[0],this.padding,this.strides[0]),n=uk(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return wi((()=>(this.invokeCallHook(e,t),this.poolingFunction(lx(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class xI extends bI{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return ob(s),ub(r),dI(e,t,n,r,s,"max")}}xI.className="MaxPooling2D",iu(xI);class wI extends bI{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return ob(s),ub(r),dI(e,t,n,r,s,"avg")}}wI.className="AveragePooling2D",iu(wI);class vI extends kx{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(3!==e.strides.length)throw new $y(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];Ky(this.poolSize,"poolSize"),Ky(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,ob(this.dataFormat),ub(this.padding),this.inputSpec=[new yx({ndim:5})]}computeOutputShape(e){e=cx(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],r="channelsFirst"===this.dataFormat?e[4]:e[3];return t=uk(t,this.poolSize[0],this.padding,this.strides[0]),n=uk(n,this.poolSize[1],this.padding,this.strides[1]),r=uk(r,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n,r]:[e[0],t,n,r,e[4]]}call(e,t){return wi((()=>(this.invokeCallHook(e,t),this.poolingFunction(lx(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class kI extends vI{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return ob(s),ub(r),fI(e,t,n,r,s,"max")}}kI.className="MaxPooling3D",iu(kI);class II extends vI{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return ob(s),ub(r),fI(e,t,n,r,s,"avg")}}II.className="AveragePooling3D",iu(II);class NI extends kx{constructor(e){super(e),this.inputSpec=[new yx({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Ey}}class SI extends NI{constructor(e){super(e||{})}call(e,t){return wi((()=>{const t=lx(e);return op(t,1)}))}}SI.className="GlobalAveragePooling1D",iu(SI);class TI extends NI{constructor(e){super(e||{})}call(e,t){return wi((()=>{const t=lx(e);return kh(t,1)}))}}TI.className="GlobalMaxPooling1D",iu(TI);class CI extends kx{constructor(e){super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,ob(this.dataFormat),this.inputSpec=[new yx({ndim:4})]}computeOutputShape(e){return"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Ey}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class $I extends CI{call(e,t){return wi((()=>{const t=lx(e);return"channelsLast"===this.dataFormat?op(t,[1,2]):op(t,[2,3])}))}}$I.className="GlobalAveragePooling2D",iu($I);class EI extends CI{call(e,t){return wi((()=>{const t=lx(e);return"channelsLast"===this.dataFormat?kh(t,[1,2]):kh(t,[2,3])}))}}EI.className="GlobalMaxPooling2D",iu(EI);class AI extends kx{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return null!=this.layer&&this.layer.trainable}set trainable(e){null!=this.layer&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){const r=xw(t.layer,n);delete t.layer;const s={layer:r};return Object.assign(s,t),new e(s)}}class RI extends AI{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=cx(e)).length<3)throw new $y(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){const t=[(e=cx(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),r=e[1];return[n[0],r].concat(n.slice(1))}call(e,t){return wi((()=>Ck(((e,n)=>[lx(this.layer.call(e,t)),[]]),e=lx(e),[],!1,null,null,!1,!0)[1]))}}RI.className="TimeDistributed",iu(RI);class OI extends AI{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=xw(n),t.goBackwards=!0!==t.goBackwards;const r={};var s;if(r.className=e.layer.getClassName(),r.config=t,this.backwardLayer=xw(r),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,s=this.mergeMode,Hy(ab,"BidirectionalMergeMode",s),e.weights)throw new Ey("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t,n,r,s=this.forwardLayer.computeOutputShape(e);return Array.isArray(s)&&Array.isArray(s[0])||(s=[s]),this.returnState?(r=s.slice(1),t=s[0]):t=s[0],"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(r).concat(r.slice()):[t].concat(r).concat(r.slice()):Dy(n)}apply(e,t){let n=null==t?null:t.initialState,r=null==t?null:t.constants;null==t&&(t={});const s=Tk(e,n,r,this.numConstants);if(e=s.inputs,n=s.initialState,r=s.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(null==n||0===n.length)&&null==r)return super.apply(e,t);const a=[],i=[];if(null!=n){const e=n.length;if(e%2>0)throw new $y("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,a.push(...n);const r=n.map((e=>new yx({shape:e.shape})));this.forwardLayer.stateSpec=r.slice(0,e/2),this.backwardLayer.stateSpec=r.slice(e/2),i.push(...r)}if(null!=r)throw new Ey("Support for constants in Bidirectional layers is not implemented yet.");const o=a[0]instanceof bx;for(const e of a)if(e instanceof bx!==o)throw new $y("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){const n=[e].concat(a),r=this.inputSpec.concat(i),s=this.inputSpec;this.inputSpec=r;const o=super.apply(n,t);return this.inputSpec=s,o}return super.apply(e,t)}call(e,t){return wi((()=>{const n=t.initialState;let r,s,a,i;if(null==n)r=this.forwardLayer.call(e,t),s=this.backwardLayer.call(e,t);else{const a=n.slice(0,n.length/2),i=n.slice(n.length/2);r=this.forwardLayer.call(e,Object.assign(t,{initialState:a})),s=this.backwardLayer.call(e,Object.assign(t,{initialState:i}))}return this.returnState&&(Array.isArray(r)&&(a=r.slice(1).concat(s.slice(1))),r=r[0],s=s[0]),this.returnSequences&&(s=Hp(s,1)),"concat"===this.mergeMode?i=Cb([r,s]):"sum"===this.mergeMode?i=Wo(r,s):"ave"===this.mergeMode?i=Go(.5,Wo(r,s)):"mul"===this.mergeMode?i=Go(r,s):null==this.mergeMode&&(i=[r,s]),this.returnState?null==this.mergeMode?i.concat(a):[i].concat(a):i}))}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){hb(this.forwardLayer.name,(()=>{this.forwardLayer.build(e)})),hb(this.backwardLayer.name,(()=>{this.backwardLayer.build(e)})),this.built=!0}computeMask(e,t){let n;if(Array.isArray(t)&&(t=t[0]),n=this.returnSequences?null==this.mergeMode?[t,t]:t:null==this.mergeMode?[null,null]:null,this.returnState){const e=this.forwardLayer.states.map((e=>null));return Array.isArray(n)?n.concat(e).concat(e):[n].concat(e).concat(e)}return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(e),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const n=xw(t.layer);if(delete t.layer,null!=t.numConstants)throw new Ey("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const r=t;return r.layer=n,new e(r)}}OI.className="Bidirectional",iu(OI);class FI extends kx{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){const e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return wi((()=>("float32"!==(e=lx(e)).dtype&&(e=kb(e,"float32")),Wo(Go(e,this.scale),this.offset))))}}FI.className="Rescaling",iu(FI);const{resizeBilinear:_I,cropAndResize:DI}=Zf;class MI extends kx{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,n,r,s,a,i,o){return wi((()=>{let u,l=!1;const c=[t/a,n/i,(r+t)/a,(s+n)/i],h=[];3===e.rank?(l=!0,u=yd([e])):u=e;for(let e=0;e<u.shape[0];e++)h.push(c);const p=ui(h,[h.length,4]),d=Up(0,h.length,1,"int32"),f=DI(u,p,d,[r,s],"nearest");return kb(l?lx(Rd(f)):f,o)}))}upsize(e,t,n,r){return wi((()=>kb(_I(e,[t,n]),r)))}call(e,t){return wi((()=>{const t=lx(e),n=t.dtype,r=t.shape,s=r[r.length-3],a=r[r.length-2];let i=0;s!==this.height&&(i=Math.floor((s-this.height)/2));let o=0;return a!==this.width&&(o=Math.floor((a-this.width)/2),0===o&&(o=1)),i>=0&&o>=0?this.centerCrop(t,i,o,this.height,this.width,s,a,n):this.upsize(e,this.height,this.width,n)}))}getConfig(){const e={height:this.height,width:this.width},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=cx(e)).length-3,n=e.length-2;return e[t]=this.height,e[n]=this.width,e}}MI.className="CenterCrop",iu(MI);class LI extends kx{constructor(e){super(e),this.numTokens=e.numTokens,e.outputMode?this.outputMode=e.outputMode:this.outputMode="multiHot"}getConfig(){const e={numTokens:this.numTokens,outputMode:this.outputMode},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){return null==(e=cx(e))?[this.numTokens]:"oneHot"===this.outputMode&&1!==e[e.length-1]?(e.push(this.numTokens),e):(e[e.length-1]=this.numTokens,e)}call(e,t){return wi((()=>{let n;if("int32"!==(e=lx(e)).dtype&&(e=kb(e,"int32")),void 0!==t.countWeights){if("count"!==this.outputMode)throw new $y(`countWeights is not used when outputMode !== count.\n Received countWeights=${t.countWeights}`);n=lx(t.countWeights)}const r=kh(e),s=Ih(e),a=Dh(this.numTokens,r).bufferSync().get(0),i=Mh(s,0).bufferSync().get(0);if(!a||!i)throw new $y(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return function(e,t,n,r){let s=lx(e);if("int32"!==s.dtype&&(s=kb(s,"int32")),"int"===t)return s;const a=s.shape;if(0===s.rank&&(s=Eh(s,-1)),"oneHot"===t&&1!==s.shape[s.shape.length-1]&&(s=Eh(s,-1)),s.rank>2)throw new $y(`When outputMode is not int, maximum output rank is 2 Received outputMode ${t} and input shape ${a} which would result in output rank ${s.rank}.`);const i=["multiHot","oneHot"].includes(t);let o;if(o=th(s,void 0!==r&&"count"===t?r:[],n,i),"tfIdf"!==t)return o;if(r)return Go(o,r);throw new $y("When outputMode is 'tfIdf', weights must be provided.")}(e,this.outputMode,this.numTokens,n)}))}}LI.className="CategoryEncoding",iu(LI);const zI=new Set(["bilinear","nearest"]);class PI extends kx{constructor(e){if(super(e),this.height=e.height,this.width=e.width,e.interpolation){if(!zI.has(e.interpolation))throw new $y(`Invalid interpolation parameter: ${e.interpolation} is not implemented`);this.interpolation=e.interpolation}else this.interpolation="bilinear";this.cropToAspectRatio=Boolean(e.cropToAspectRatio)}computeOutputShape(e){const t=(e=cx(e))[2];return[this.height,this.width,t]}getConfig(){const e={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return wi((()=>{const t=[this.height,this.width];if("bilinear"===this.interpolation)return Zf.resizeBilinear(e,t,!this.cropToAspectRatio);if("nearest"===this.interpolation)return Zf.resizeNearestNeighbor(e,t,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...zI]} are supported`)}))}}PI.className="Resizing",iu(PI);class BI{constructor(e){this.seed=e}next(){if(void 0!==this.seed)return this.seed++}}BI.className="RandomSeed";class WI extends kx{constructor(e){super(e),this.randomGenerator=new BI(e.seed)}getConfig(){const e={seed:this.randomGenerator.seed},t=super.getConfig();return Object.assign(e,t),e}}WI.className="BaseRandomLayer";const UI=new Set(["bilinear","nearest"]);class VI extends WI{constructor(e){super(e);const{factor:t,interpolation:n="bilinear"}=e;if(this.factor=t,Array.isArray(this.factor)&&2===this.factor.length)this.widthLower=this.factor[0],this.widthUpper=this.factor[1];else{if(Array.isArray(this.factor)||!(this.factor>0))throw new $y(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);this.widthLower=-this.factor,this.widthUpper=this.factor}if(this.widthLower<-1||this.widthUpper<-1)throw new $y(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper<this.widthLower)throw new $y(`factor cannot have upper bound less than lower bound.\n Got upper bound: ${this.widthUpper}.\n Got lower bound: ${this.widthLower}\n `);if(n){if(!UI.has(n))throw new $y(`Invalid interpolation parameter: ${n} is not implemented`);this.interpolation=n}}getConfig(){const e={factor:this.factor,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=cx(e))[2];return[this.imgHeight,-1,t]}call(e,t){return wi((()=>{const t=lx(e);this.imgHeight=t.shape[t.shape.length-3];const n=t.shape[t.shape.length-2];this.widthFactor=Bp([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let r=this.widthFactor.dataSync()[0]*n;r=Math.round(r);const s=[this.imgHeight,r];switch(this.interpolation){case"bilinear":return Zf.resizeBilinear(e,s);case"nearest":return Zf.resizeNearestNeighbor(e,s);default:throw new Error(`Interpolation is ${this.interpolation}\n but only ${[...UI]} are supported`)}}))}}function GI(e){return new Nx(e)}function jI(e){return new sk(e)}function HI(e){return new tk(e)}function qI(e){return new nk(e)}function KI(e){return new rk(e)}function XI(e){return new ik(e)}function YI(e){return new ak(e)}function JI(e){return new vk(e)}function ZI(e){return new mk(e)}function QI(e){return new yk(e)}function eN(e){return new gk(e)}function tN(e){return new bk(e)}function nN(e){return new wk(e)}function rN(e){return new kk(e)}function sN(e){return new Ik(e)}function aN(e){return new Nk(e)}function iN(e){return new jk(e)}function oN(e){return new Vk(e)}function uN(e){return new Wk(e)}function lN(e){return new Uk(e)}function cN(e){return new Gk(e)}function hN(e){return new Hk(e)}function pN(e){return new qk(e)}function dN(e){return new Kk(e)}function fN(e){return new Yk(e)}function mN(e){return new Zk(e)}function gN(e){return new eI(e)}function yN(e){return new rI(e)}function bN(e){return new tI(e)}function xN(e){return new nI(e)}function wN(e){return new Qk(e)}function vN(e){return new aI(e)}function kN(e){return new cI(e)}function IN(e){return new hI(e)}function NN(e){return new pI(e)}function SN(e){return new yI(e)}function TN(e){return SN(e)}function CN(e){return SN(e)}function $N(e){return new wI(e)}function EN(e){return $N(e)}function AN(e){return $N(e)}function RN(e){return new II(e)}function ON(e){return RN(e)}function FN(e){return RN(e)}function _N(e){return new SI(e)}function DN(e){return new $I(e)}function MN(e){return new TI(e)}function LN(e){return new EI(e)}function zN(e){return new gI(e)}function PN(e){return new xI(e)}function BN(e){return new kI(e)}function WN(e){return new Fk(e)}function UN(e){return new Ok(e)}function VN(e){return new Dk(e)}function GN(e){return new _k(e)}function jN(e){return new Rk(e)}function HN(e){return new Ak(e)}function qN(e){return new Bk(e)}function KN(e){return new Pk(e)}function XN(e){return new $k(e)}function YN(e){return new Mk(e)}function JN(e){return new OI(e)}function ZN(e){return new RI(e)}VI.className="RandomWidth",iu(VI);const QN=MN,eS=LN,tS=zN,nS=PN;function rS(e){return new iI(e)}function sS(e){return new oI(e)}function aS(e){return new uI(e)}function iS(e){return new Xk(e)}function oS(e){return new FI(e)}function uS(e){return new MI(e)}function lS(e){return new PI(e)}function cS(e){return new LI(e)}function hS(e){return new VI(e)}function pS(e,t){return Aw(e,t)}function dS(e,t){return _w(e,t)}function fS(e,t){return Dw(e,t)}function mS(e,t){return Rw(e,t)}function gS(e,t){return Mw(e,t)}function yS(e,t){return Fw(e,t)}function bS(e,t){return function(e,t){return wi((()=>{const n=Ow(e,t),r=function(e,t){return wi((()=>Lo(Nh(Jh(ih(e,1),ih(t,0))),"float32")))}(e,t),s=Wo(n,r);return Lo(oh(Dh(s,0),Vo(n,s),0),"float32")}))}(e,t)}function xS(e,t){return Cw(e,t)}function wS(e,t){return kw(e,t)}function vS(e,t){return Iw(e,t)}function kS(e,t){return Iw(e,t)}function IS(e,t){return Iw(e,t)}function NS(e,t){return vw(e,t)}function SS(e,t){return vw(e,t)}function TS(e,t){return vw(e,t)}function CS(e){return new Yv(e)}function $S(e){return Kv(t=e),new Yv({l1:null!=t?t.l1:null,l2:0});var t}function ES(e){return Kv(t=e),new Yv({l2:null!=t?t.l2:null,l1:0});var t}var AS=n(96763);class RS extends hw{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof bv))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function OS(e,t){return e<t}function FS(e,t){return e>t}class _S extends RS{constructor(e){if(super(),null==e&&(e={}),e.restoreBestWeights)throw new Ey("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.baseline,-1===["auto","min","max"].indexOf(this.mode)&&(AS.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),"min"===this.mode?this.monitorFunc=OS:"max"===this.mode||-1!==this.monitor.indexOf("acc")?this.monitorFunc=FS:this.monitorFunc=OS,this.monitorFunc===OS&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,null!=this.baseline?this.best=this.baseline:this.best=this.monitorFunc===OS?1/0:-1/0}async onEpochEnd(e,t){await uw(t);const n=this.getMonitorValue(t);null!=n&&(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&AS.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){null==e&&(e={});const t=e[this.monitor];return null==t&&AS.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}}const DS={earlyStopping:function(e){return new _S(e)}};var MS,LS,zS=n(96763);Ye().registerFlag("KEEP_INTERMEDIATE_TENSORS",(()=>!1),(e=>{e&&zS.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")})),function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_QINT16=15]="DT_QINT16",e[e.DT_QUINT16=16]="DT_QUINT16",e[e.DT_UINT16=17]="DT_UINT16",e[e.DT_COMPLEX128=18]="DT_COMPLEX128",e[e.DT_HALF=19]="DT_HALF",e[e.DT_RESOURCE=20]="DT_RESOURCE",e[e.DT_VARIANT=21]="DT_VARIANT",e[e.DT_UINT32=22]="DT_UINT32",e[e.DT_UINT64=23]="DT_UINT64",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",e[e.DT_QINT16_REF=115]="DT_QINT16_REF",e[e.DT_QUINT16_REF=116]="DT_QUINT16_REF",e[e.DT_UINT16_REF=117]="DT_UINT16_REF",e[e.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",e[e.DT_HALF_REF=119]="DT_HALF_REF",e[e.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",e[e.DT_VARIANT_REF=121]="DT_VARIANT_REF",e[e.DT_UINT32_REF=122]="DT_UINT32_REF",e[e.DT_UINT64_REF=123]="DT_UINT64_REF"}(MS||(MS={})),function(e){let t;!function(e){e[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"}(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))}(LS||(LS={}));const PS={};function BS(e,t){const n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};PS[e]=n}function WS(e){return PS[e]}function US(e){delete PS[e]}function VS(e,t,n,r,s){const a=t.inputParams[e];if(a&&void 0!==a.inputIndexStart){const e=a.inputIndexStart,i=0===a.inputIndexEnd?void 0:void 0===a.inputIndexEnd?e+1:a.inputIndexEnd,o=e<0?t.inputNames.length+e:e;if("tensor"===a.type)return GS(t.inputNames[o],n,r,s);if("tensors"===a.type){const a=t.inputs.slice(e,i);return t.inputNames.slice(e,i).filter(((e,t)=>{var n;return"NoOp"!==(null===(n=a[t])||void 0===n?void 0:n.op)})).map((e=>GS(e,n,r,s)))}const u=GS(t.inputNames[o],n,r,s),l=u.dataSync();return"number"===a.type?l[0]:Le(u.shape,l)}const i=t.attrParams[e];return i&&i.value}function GS(e,t,n,r){const[s,a]=KS(e,n);if(null!=r){const e=r.getHashTableHandleByName(s);if(null!=e)return e}const i=n.currentContextIds.find((e=>!!t[qS(s,e)]));return void 0!==i?t[qS(s,i)][a]:void 0}function jS(e,t,n){return t[qS(e,n.currentContextId)]}function HS(e,t){const[n,r,s]=KS(e,t);return[qS(n,t&&t.currentContextId),r,s]}function qS(e,t){return t?`${e}-${t}`:e}function KS(e,t){if(""===e)return["",0,void 0];const n=null!=t&&null!=t.parseNodeNameCache;if(n){const n=t.parseNodeNameCache.get(e);if(null!=n)return n}const r=e.split(":");let s;if(1===r.length)s=[e,0,void 0];else{const e=r[0],t=3===r.length?r[1]:void 0;s=[e,Number(r[r.length-1]),t]}return n&&t.parseNodeNameCache.set(e,s),s}function XS(e,t,n){let r=VS("pad",e,t,n);if("explicit"===r){r=VS("explicitPaddings",e,t,n);const s=[[0,0],[0,0],[0,0],[0,0]];for(let e=0;e<4;e++)s[e][0]=r[2*e],s[e][1]=r[2*e+1];return s}return r}function YS(e){return e.kept?e:zo(e)}const JS=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],ZS=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsFinite",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsInf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],QS=[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcatV2",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}],eT=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}],tT=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniformInt",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number"},{tfName:"maxval",name:"maxval",type:"number"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}],nT=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],rT=[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}],sT=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}],aT=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"InitializeTable",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]},{tfOpName:"InitializeTableV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]}],iT=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}],oT=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BitwiseAnd",category:"logical",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}]}],uT=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"MatrixBandPart",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"numLower",type:"tensor"},{start:1,name:"numUpper",type:"tensor"}]}],lT=[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]}],cT=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cumprod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}],hT=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]},{tfOpName:"TensorScatterUpdate",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"values",type:"tensor"}]}],pT=[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}],dT=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}],fT=[{tfOpName:"StaticRegexReplace",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"pattern",name:"pattern",type:"string"},{tfName:"rewrite",name:"rewrite",type:"string"},{tfName:"replace_global",name:"replaceGlobal",type:"bool"}]},{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}],mT=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"EnsureShape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}];var gT=n(62045).hp;class yT{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[S,T,C,$,E,A,R,O,F,_,D,M,L,z,P,B,W,U,V].map((e=>e.json)));this.opMappers=e.reduce(((e,t)=>(e[t.tfOpName]=t,e)),{})}transformGraph(e,t={}){const n=e.node,r=[],s=[],a=[],i=n.reduce(((e,t)=>(e[t.name]=this.mapNode(t),t.op.startsWith("Placeholder")?r.push(e[t.name]):"Const"===t.op?s.push(e[t.name]):null!=t.input&&0!==t.input.length||a.push(e[t.name]),e)),{});let o=[];const u=[];let l={},c={};null!=t&&(l=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));const h=Object.keys(i);h.forEach((e=>{const t=i[e];t.inputNames.forEach(((e,n)=>{const[r,,s]=HS(e),a=i[r];if(null!=a.outputs){const e=a.outputs.indexOf(s);if(-1!==e){const s=`${r}:${e}`;t.inputNames[n]=s}}t.inputs.push(a),a.children.push(t)}))})),0===Object.keys(c).length?h.forEach((e=>{const t=i[e];0===t.children.length&&u.push(t)})):Object.keys(c).forEach((e=>{const[t]=HS(e),n=i[t];null!=n&&(n.signatureKey=c[e],u.push(n))})),Object.keys(l).length>0?Object.keys(l).forEach((e=>{const[t]=HS(e),n=i[t];n&&(n.signatureKey=l[e],o.push(n))})):o=r;let p={};null!=e.library&&null!=e.library.function&&(p=e.library.function.reduce(((e,t)=>(e[t.signature.name]=this.mapFunction(t),e)),{}));const d={nodes:i,inputs:o,outputs:u,weights:s,placeholders:r,signature:t,functions:p};return a.length>0&&(d.initNodes=a),d}mapSignatureEntries(e){return Object.keys(e||{}).reduce(((t,n)=>(t[e[n].name]=n,t)),{})}mapNode(e){const t=WS(e.op)||this.opMappers[e.op]||{};null==e.attr&&(e.attr={});const n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map((e=>e.startsWith("^")?e.slice(1):e)),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return null!=t.inputs&&(n.inputParams=t.inputs.reduce(((e,t)=>(e[t.name]={type:t.type,inputIndexStart:t.start,inputIndexEnd:t.end},e)),{})),null!=t.attrs&&(n.attrParams=t.attrs.reduce(((t,n)=>{const r=n.type;let s;switch(n.type){case"string":s=xT(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=xT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":s=ET(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=ET(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":s=vT(e.attr,n.tfName,n.defaultValue||0),void 0===s&&n.tfDeprecatedName&&(s=vT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":s=$T(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=$T(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":s=wT(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=wT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":s=RT(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=RT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":s=CT(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=CT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":s=AT(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=AT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":s=NT(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=NT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":s=ST(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=ST(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":s=IT(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=IT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${n.type} for op: ${e.op}`)}return t[n.name]={value:s,type:r},t}),{})),n}mapFunction(e){const t=e.nodeDef,n=[];let r={};null!=t&&(r=t.reduce(((e,t)=>(e[t.name]=this.mapNode(t),"Const"===t.op&&n.push(e[t.name]),e)),{}));const s=[],a=[];e.signature.inputArg.forEach((e=>{const[t]=HS(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:kT(e.type),type:"dtype"}},children:[]};n.signatureKey=e.name,s.push(n),r[t]=n})),Object.keys(r).forEach((e=>{const t=r[e];t.inputNames.forEach(((e,n)=>{const[s,,a]=HS(e),i=r[s];if(null!=i.outputs){const e=i.outputs.indexOf(a);if(-1!==e){const r=`${s}:${e}`;t.inputNames[n]=r}}t.inputs.push(i),i.children.push(t)}))}));const i=e.ret;e.signature.outputArg.forEach((e=>{const[t,n]=HS(i[e.name]),s=r[t];null!=s&&(s.defaultOutput=n,a.push(s))}));const o=this.mapArgsToSignature(e);return{nodes:r,inputs:s,outputs:a,weights:n,placeholders:[],signature:o}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce(((e,t)=>(e[t.name]=this.mapArgToTensorInfo(t),e)),{}),outputs:e.signature.outputArg.reduce(((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t)),{})}}mapArgToTensorInfo(e,t){let n=e.name;return null!=t&&(n=t[n]),{name:n,dtype:e.type}}}function bT(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=Ye().global;if(void 0!==t.atob)return t.atob(e);if(void 0!==gT)return new gT(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}(e);return t?n:n.toLowerCase()}function xT(e,t,n,r=!1){const s=e[t];return null!=s?bT(s.s,r):n}function wT(e,t,n){const r=e[t];return r?r.b:n}function vT(e,t,n){const r=e[t]||{},s=null!=r.i?r.i:null!=r.f?r.f:n;return"number"==typeof s?s:parseInt(s,10)}function kT(e){switch("string"==typeof e&&(e=MS[e]),e){case MS.DT_FLOAT:case MS.DT_HALF:return"float32";case MS.DT_INT32:case MS.DT_INT64:case MS.DT_INT8:case MS.DT_UINT8:return"int32";case MS.DT_BOOL:return"bool";case MS.DT_DOUBLE:return"float32";case MS.DT_STRING:return"string";case MS.DT_COMPLEX64:case MS.DT_COMPLEX128:return"complex64";default:return null}}function IT(e,t,n){const r=e[t];return r&&r.func?r.func.name:n}function NT(e,t,n){const r=e[t];return r&&r.type?kT(r.type):n}function ST(e,t,n){const r=e[t];return r&&r.list&&r.list.type?r.list.type.map((e=>kT(e))):n}function TT(e){if(!e.unknownRank)return null!=e.dim?e.dim.map((e=>"number"==typeof e.size?e.size:parseInt(e.size,10))):[]}function CT(e,t,n){const r=e[t];return r&&r.shape?TT(r.shape):n}function $T(e,t,n){const r=e[t];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map((e=>"number"==typeof e?e:parseInt(e,10))):n}function ET(e,t,n,r=!1){const s=e[t];return s&&s.list&&s.list.s?s.list.s.map((e=>bT(e,r))):n}function AT(e,t,n){const r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map((e=>TT(e))):n}function RT(e,t,n){const r=e[t];return r&&r.list&&r.list.b?r.list.b:n}class OT{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map((e=>this.getInput(e))),null!=e.rawAttrs&&(this.attrs=Object.keys(e.rawAttrs).reduce(((e,t)=>(e[t]=this.getAttr(t),e)),{}))}getInput(e){return GS(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return GS(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return vT(this.node.rawAttrs,e,t);if(null!=n.s)return xT(this.node.rawAttrs,e,t);if(null!=n.b)return wT(this.node.rawAttrs,e,t);if(null!=n.shape)return CT(this.node.rawAttrs,e,t);if(null!=n.type)return NT(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return $T(this.node.rawAttrs,e,t);if(null!=n.list.s)return ET(this.node.rawAttrs,e,t);if(null!=n.list.shape)return AT(this.node.rawAttrs,e,t);if(null!=n.list.b)return RT(this.node.rawAttrs,e,t);if(null!=n.list.type)return ST(this.node.rawAttrs,e,t)}return t}}function FT(e,t,n=""){if("number"!=typeof e&&"number"!=typeof t){ie(e.length===t.length,(()=>n+` Shapes ${e} and ${t} must match`));for(let r=0;r<e.length;r++){const s=e[r],a=t[r];ie(s<0||a<0||s===a,(()=>n+` Shapes ${e} and ${t} must match`))}}}function _T(e){return"number"!=typeof e&&!e.some((e=>e<0))}function DT(e,t,n){let r=MT(e,n);const s=!_T(r);if(s&&0===t.length)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${r}`);if(s&&t.forEach((e=>{r=MT(e.shape,r)})),!_T(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function MT(e,t){if("number"==typeof e)return t;if("number"==typeof t)return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);const n=[];for(let r=0;r<e.length;++r){const s=e[r],a=t[r];if(s>=0&&a>=0&&s!==a)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[r]=s>=0?s:a}return n}class LT{constructor(e,t,n,r,s,a,i){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=r,this.identicalElementShapes=s,this.dynamicSize=a,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=tu(0),ki(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach((t=>{null!=e&&e.has(t.tensor.id)||t.tensor.dispose()})),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);const t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map((e=>this.read(e)))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);const n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},\n because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),FT(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,ki(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach(((e,n)=>this.write(e,t[n])))}gather(e,t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let t=0;t<this.size();t++)e.push(t)}if(0===e.length)return ui([],[0].concat(this.elementShape));const n=this.readMany(e);return FT(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),yd(n,0)}concat(e){if(e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(0===this.size())return ui([],[0].concat(this.elementShape));const t=[];for(let e=0;e<this.size();e++)t.push(e);const n=this.readMany(t);return FT(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Nc(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);const n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,Rd(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0;const r=e.map((e=>(n+=e,n)));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const s=0===n?0:t.size/n,a=[];wi((()=>{t=vc(t,[1,n,s]);for(let n=0;n<e.length;++n){const i=[0,0===n?0:r[n-1],0],o=[1,e[n],s];a[n]=vc(Tc(t,i,o),this.elementShape)}return a}));const i=[];for(let t=0;t<e.length;t++)i[t]=t;this.writeMany(i,a)}}class zT{get id(){return this.idTensor.id}constructor(e,t,n,r=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,null!=e&&e.forEach((e=>{if(n!==e.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${e.dtype}`);FT(t,e.shape,"TensorList shape mismatch: "),ki(e)})),this.idTensor=tu(0),this.maxNumElements=r,ki(this.idTensor)}copy(){return new zT([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach((t=>{null!=e&&e.has(t.id)||t.dispose()})),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(-1!==n&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);FT(e,this.elementShape,"TensorList shape mismatch: ");const r=DT(this.elementShape,this.tensors,e);return wi((()=>{const e=this.tensors.map((e=>vc(e,r)));return yd(e,0)}))}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(0===this.size())throw new Error("Trying to pop from an empty list.");const n=DT(this.elementShape,this.tensors,e),r=this.tensors.pop();return r.kept=!1,FT(r.shape,e,"TensorList shape mismatch: "),vc(r,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(FT(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");ki(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(-1!==this.maxNumElements&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);const t=new zT([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;n<Math.min(this.tensors.length,e);++n)t.tensors[n]=this.tensors[n];return t}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(null==this.tensors[e])throw new Error(`element at index ${e} is null.`);FT(this.tensors[e].shape,t,"TensorList shape mismatch: ");const r=DT(this.elementShape,this.tensors,t);return vc(this.tensors[e],r)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||-1!==this.maxNumElements&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);FT(this.elementShape,t.shape,"TensorList shape mismatch: "),ki(t),null!=this.tensors[e]&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);FT(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const r=DT(this.elementShape,this.tensors,n);return 0===e.length?ui([],[0].concat(r)):wi((()=>{const t=e.map((e=>vc(this.tensors[e],r)));return yd(t,0)}))}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);FT(this.elementShape,t,"TensorList shape mismatch: ");const n=DT(this.elementShape,this.tensors,t);return 0===this.size()?ui([],[0].concat(n)):wi((()=>{const e=this.tensors.map((e=>vc(e,n)));return Nc(e,0)}))}}function PT(e,t,n){const[r,s]=VS("fusedOps",e,t,n),a="biasadd"===r,i=!a,o="prelu"===s,u="fusedbatchnorm"===r,l=VS("numArgs",e,t,n);if(a){if(o&&2!==l)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&a&&1!==l)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(u)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");const c=VS("strides",e,t,n),h=XS(e,t,n),p=VS("dataFormat",e,t,n).toUpperCase(),d=VS("dilations",e,t,n);let[f,m]=VS("args",e,t,n);return i&&(m=f,f=void 0),{stride:c,pad:h,dataFormat:p,dilations:d,biasArg:f,preluArg:m,activationFunc:s,leakyreluAlpha:VS("leakyreluAlpha",e,t,n)}}function BT(e,t,n){return{boxes:VS("boxes",e,t,n),scores:VS("scores",e,t,n),maxOutputSize:VS("maxOutputSize",e,t,n),iouThreshold:VS("iouThreshold",e,t,n),scoreThreshold:VS("scoreThreshold",e,t,n),softNmsSigma:VS("softNmsSigma",e,t,n)}}var WT=n(96763);class UT{get id(){return this.handle.id}constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=tu(0),this.tensorMap=new Map,ki(this.handle)}clearAndClose(){this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return tu(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),wi((()=>{const e=Rd(t),r=n.length,s=e.length;ie(r===s,(()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${s} elements.`));for(let t=0;t<r;t++){const r=n[t],s=e[t];ki(s),this.tensorMap.set(r,s)}return this.handle}))}async find(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return wi((()=>{const e=[];for(let r=0;r<n.length;r++){const s=n[r],a=this.findWithDefault(s,t);e.push(a)}return yd(e)}))}findWithDefault(e,t){const n=this.tensorMap.get(e);return null!=n?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}}function VT(e,t,n,r,s=wi){const a=((e,t,n)=>{switch(e.category){case"arithmetic":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[r.add(VS("a",e,t,n),VS("b",e,t,n))];case"AddN":return[r.addN(VS("tensors",e,t,n))];case"FloorMod":case"Mod":return[r.mod(VS("a",e,t,n),VS("b",e,t,n))];case"Mul":return[r.mul(VS("a",e,t,n),VS("b",e,t,n))];case"RealDiv":case"Div":return[r.div(VS("a",e,t,n),VS("b",e,t,n))];case"DivNoNan":return[r.divNoNan(VS("a",e,t,n),VS("b",e,t,n))];case"FloorDiv":return[r.floorDiv(VS("a",e,t,n),VS("b",e,t,n))];case"Sub":return[r.sub(VS("a",e,t,n),VS("b",e,t,n))];case"Minimum":return[r.minimum(VS("a",e,t,n),VS("b",e,t,n))];case"Maximum":return[r.maximum(VS("a",e,t,n),VS("b",e,t,n))];case"Pow":return[r.pow(VS("a",e,t,n),VS("b",e,t,n))];case"SquaredDifference":return[r.squaredDifference(VS("a",e,t,n),VS("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"basic_math":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"Abs":case"ComplexAbs":return[r.abs(VS("x",e,t,n))];case"Acos":return[r.acos(VS("x",e,t,n))];case"Acosh":return[r.acosh(VS("x",e,t,n))];case"Asin":return[r.asin(VS("x",e,t,n))];case"Asinh":return[r.asinh(VS("x",e,t,n))];case"Atan":return[r.atan(VS("x",e,t,n))];case"Atan2":return[r.atan2(VS("x",e,t,n),VS("y",e,t,n))];case"Atanh":return[r.atanh(VS("x",e,t,n))];case"Ceil":return[r.ceil(VS("x",e,t,n))];case"Complex":return[r.complex(VS("real",e,t,n),VS("imag",e,t,n))];case"Cos":return[r.cos(VS("x",e,t,n))];case"Cosh":return[r.cosh(VS("x",e,t,n))];case"Elu":return[r.elu(VS("x",e,t,n))];case"Erf":return[r.erf(VS("x",e,t,n))];case"Exp":return[r.exp(VS("x",e,t,n))];case"Expm1":return[r.expm1(VS("x",e,t,n))];case"Floor":return[r.floor(VS("x",e,t,n))];case"Log":return[r.log(VS("x",e,t,n))];case"Log1p":return[r.log1p(VS("x",e,t,n))];case"Imag":return[r.imag(VS("x",e,t,n))];case"Neg":return[r.neg(VS("x",e,t,n))];case"Reciprocal":return[r.reciprocal(VS("x",e,t,n))];case"Real":return[r.real(VS("x",e,t,n))];case"Relu":return[r.relu(VS("x",e,t,n))];case"Round":return[r.round(VS("x",e,t,n))];case"Selu":return[r.selu(VS("x",e,t,n))];case"Sigmoid":return[r.sigmoid(VS("x",e,t,n))];case"Sin":return[r.sin(VS("x",e,t,n))];case"Sign":return[r.sign(VS("x",e,t,n))];case"Sinh":return[r.sinh(VS("x",e,t,n))];case"Softplus":return[r.softplus(VS("x",e,t,n))];case"Sqrt":return[r.sqrt(VS("x",e,t,n))];case"Square":return[r.square(VS("x",e,t,n))];case"Tanh":return[r.tanh(VS("x",e,t,n))];case"Tan":return[r.tan(VS("x",e,t,n))];case"ClipByValue":return[r.clipByValue(VS("x",e,t,n),VS("clipValueMin",e,t,n),VS("clipValueMax",e,t,n))];case"Relu6":return[r.relu6(VS("x",e,t,n))];case"Rsqrt":return[r.rsqrt(GS(e.inputNames[0],t,n))];case"LeakyRelu":return[r.leakyRelu(VS("x",e,t,n),VS("alpha",e,t,n))];case"Prelu":return[r.prelu(VS("x",e,t,n),VS("alpha",e,t,n))];case"IsNan":return[r.isNaN(GS(e.inputNames[0],t,n))];case"IsInf":return[r.isInf(GS(e.inputNames[0],t,n))];case"IsFinite":return[r.isFinite(GS(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"control":return(async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const r=VS("thenBranch",e,t,n),s=VS("elseBranch",e,t,n),a=VS("cond",e,t,n),i=VS("args",e,t,n);return(await a.data())[0]?n.functionMap[r].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap):n.functionMap[s].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const r=VS("body",e,t,n),s=VS("cond",e,t,n),a=VS("args",e,t,n),i=await n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),o=a.map((e=>e.id));let u=await i[0].data();i.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||e.dispose()}));let l=a;for(;u[0];){const e=l;l=await n.functionMap[r].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);const t=l.map((e=>e.id));e.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}));const a=await n.functionMap[s].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);u=await a[0].data(),a.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}))}return l}case"LoopCond":return[YS(VS("pred",e,t,n))];case"Switch":{const r=VS("pred",e,t,n);let s=VS("data",e,t,n);return s.kept||(s=YS(s)),(await r.data())[0]?[void 0,s]:[s,void 0]}case"Merge":{const r=e.inputNames.find((e=>void 0!==GS(e,t,n)));return r?[YS(GS(r,t,n))]:void 0}case"Enter":{const r=VS("frameName",e,t,n),s=VS("tensor",e,t,n);return n.enterFrame(r),[YS(s)]}case"Exit":{const r=VS("tensor",e,t,n);return n.exitFrame(),[YS(r)]}case"NextIteration":{const r=VS("tensor",e,t,n);return n.nextIteration(),[YS(r)]}case"TensorArrayV3":{const r=VS("size",e,t,n),s=VS("dtype",e,t,n),a=VS("elementShape",e,t,n),i=VS("dynamicSize",e,t,n),o=VS("clearAfterRead",e,t,n),u=VS("identicalElementShapes",e,t,n),l=VS("name",e,t,n),c=new LT(l,s,r,a,u,i,o);return n.addTensorArray(c),[c.idTensor,tu(1)]}case"TensorArrayWriteV3":{const r=VS("tensorArrayId",e,t,n),s=VS("index",e,t,n),a=VS("tensor",e,t,n),i=n.getTensorArray(r.id);return i.write(s,a),[i.idTensor]}case"TensorArrayReadV3":{const r=VS("tensorArrayId",e,t,n),s=VS("index",e,t,n);return[n.getTensorArray(r.id).read(s)]}case"TensorArrayGatherV3":{const r=VS("tensorArrayId",e,t,n),s=VS("indices",e,t,n),a=VS("dtype",e,t,n);return[n.getTensorArray(r.id).gather(s,a)]}case"TensorArrayScatterV3":{const r=VS("tensorArrayId",e,t,n),s=VS("indices",e,t,n),a=VS("tensor",e,t,n),i=n.getTensorArray(r.id);return i.scatter(s,a),[i.idTensor]}case"TensorArrayConcatV3":{const r=VS("tensorArrayId",e,t,n),s=n.getTensorArray(r.id),a=VS("dtype",e,t,n);return[s.concat(a)]}case"TensorArraySplitV3":{const r=VS("tensorArrayId",e,t,n),s=VS("tensor",e,t,n),a=VS("lengths",e,t,n),i=n.getTensorArray(r.id);return i.split(a,s),[i.idTensor]}case"TensorArraySizeV3":{const r=VS("tensorArrayId",e,t,n);return[tu(n.getTensorArray(r.id).size(),"int32")]}case"TensorArrayCloseV3":{const r=VS("tensorArrayId",e,t,n),s=n.getTensorArray(r.id);return s.clearAndClose(),[s.idTensor]}case"TensorListSetItem":{const r=VS("tensorListId",e,t,n),s=VS("index",e,t,n),a=VS("tensor",e,t,n),i=n.getTensorList(r.id);return i.setItem(s,a),[i.idTensor]}case"TensorListGetItem":{const r=VS("tensorListId",e,t,n),s=VS("index",e,t,n),a=VS("elementShape",e,t,n),i=VS("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(s,a,i)]}case"TensorListScatterV2":case"TensorListScatter":{const r=VS("indices",e,t,n),s=function(e,t,n,r){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const s=Math.max(...t);if(null!=r&&-1!==r&&s>=r)throw new Error(`Max index must be < array size (${s} vs. ${r})`);const a=new zT([],n,e.dtype,r),i=Rd(e,0);return t.forEach(((e,t)=>{a.setItem(e,i[t])})),a}(VS("tensor",e,t,n),r,VS("elementShape",e,t,n),VS("numElements",e,t,n));return n.addTensorList(s),[s.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const r=VS("elementShape",e,t,n),s=VS("elementDType",e,t,n);let a;a="TensorListReserve"===e.op?"numElements":"maxNumElements";const i=VS(a,e,t,n),o=function(e,t,n,r){return new zT([],e,t,r)}(r,s,0,"TensorListReserve"===e.op?-1:i);return n.addTensorList(o),[o.idTensor]}case"TensorListGather":{const r=VS("tensorListId",e,t,n),s=VS("indices",e,t,n),a=VS("elementShape",e,t,n),i=VS("elementDType",e,t,n);return[n.getTensorList(r.id).gather(s,i,a)]}case"TensorListStack":{const r=VS("tensorListId",e,t,n),s=VS("elementShape",e,t,n),a=VS("elementDType",e,t,n),i=VS("numElements",e,t,n);return[n.getTensorList(r.id).stack(s,a,i)]}case"TensorListFromTensor":{const r=function(e,t,n){const r=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);FT(e.shape.slice(1),t,"TensorList shape mismatch: ");const s=Rd(e);return new zT(s,t,r)}(VS("tensor",e,t,n),VS("elementShape",e,t,n),VS("elementDType",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const r=VS("tensorListId",e,t,n),s=n.getTensorList(r.id),a=VS("dtype",e,t,n),i=VS("elementShape",e,t,n);return[s.concat(a,i)]}case"TensorListPushBack":{const r=VS("tensorListId",e,t,n),s=VS("tensor",e,t,n),a=n.getTensorList(r.id);return a.pushBack(s),[a.idTensor]}case"TensorListPopBack":{const r=VS("tensorListId",e,t,n),s=VS("elementShape",e,t,n),a=VS("elementDType",e,t,n);return[n.getTensorList(r.id).popBack(s,a)]}case"TensorListSplit":{const r=VS("tensor",e,t,n),s=VS("elementShape",e,t,n),a=function(e,t,n){let r=0;const s=t.map((e=>(r+=e,r)));if(r!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${r}, and tensor's shape is: ${e.shape}`);const a=MT(e.shape.slice(1),n),i=0===r?0:e.size/r,o=wi((()=>{const n=[];e=vc(e,[1,r,i]);for(let r=0;r<t.length;++r){const o=[0,0===r?0:s[r-1],0],u=[1,t[r],i];n[r]=vc(Tc(e,o,u),a)}return e.dispose(),n})),u=new zT([],n,e.dtype,t.length);for(let e=0;e<o.length;e++)u.setItem(e,o[e]);return u}(r,VS("lengths",e,t,n),s);return n.addTensorList(a),[a.idTensor]}case"TensorListLength":{const r=VS("tensorListId",e,t,n);return[tu(n.getTensorList(r.id).size(),"int32")]}case"TensorListResize":{const r=VS("tensorListId",e,t,n),s=VS("size",e,t,n),a=n.getTensorList(r.id).resize(s);return n.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"convolution":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"Conv1D":{const s=VS("stride",e,t,n),a=VS("pad",e,t,n),i=VS("dataFormat",e,t,n).toUpperCase(),o=VS("dilation",e,t,n);return[r.conv1d(VS("x",e,t,n),VS("filter",e,t,n),s,a,i,o)]}case"Conv2D":{const s=VS("strides",e,t,n),a=XS(e,t,n),i=VS("dataFormat",e,t,n).toUpperCase(),o=VS("dilations",e,t,n);return[r.conv2d(VS("x",e,t,n),VS("filter",e,t,n),[s[1],s[2]],a,i,[o[1],o[2]])]}case"_FusedConv2D":{const{stride:s,pad:a,dataFormat:i,dilations:o,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:h}=PT(e,t,n);return[r.fused.conv2d({x:VS("x",e,t,n),filter:VS("filter",e,t,n),strides:[s[1],s[2]],pad:a,dataFormat:i,dilations:[o[1],o[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:h})]}case"FusedDepthwiseConv2dNative":{const{stride:s,pad:a,dataFormat:i,dilations:o,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:h}=PT(e,t,n);return[r.fused.depthwiseConv2d({x:VS("x",e,t,n),filter:VS("filter",e,t,n),strides:[s[1],s[2]],pad:a,dataFormat:i,dilations:[o[1],o[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:h})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const s=VS("outputShape",e,t,n),a=VS("strides",e,t,n),i=XS(e,t,n);return[r.conv2dTranspose(VS("x",e,t,n),VS("filter",e,t,n),s,[a[1],a[2]],i)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const s=VS("strides",e,t,n),a=XS(e,t,n),i=VS("dilations",e,t,n),o=VS("dataFormat",e,t,n).toUpperCase();return[r.depthwiseConv2d(VS("input",e,t,n),VS("filter",e,t,n),[s[1],s[2]],a,o,[i[1],i[2]])]}case"Conv3D":{const s=VS("strides",e,t,n),a=VS("pad",e,t,n),i=VS("dataFormat",e,t,n).toUpperCase(),o=VS("dilations",e,t,n);return[r.conv3d(VS("x",e,t,n),VS("filter",e,t,n),[s[1],s[2],s[3]],a,i,[o[1],o[2],o[3]])]}case"AvgPool":{const s=VS("strides",e,t,n),a=VS("pad",e,t,n),i=VS("kernelSize",e,t,n);return[r.avgPool(VS("x",e,t,n),[i[1],i[2]],[s[1],s[2]],a)]}case"MaxPool":{const s=VS("strides",e,t,n),a=VS("pad",e,t,n),i=VS("kernelSize",e,t,n);return[r.maxPool(VS("x",e,t,n),[i[1],i[2]],[s[1],s[2]],a)]}case"MaxPoolWithArgmax":{const s=VS("strides",e,t,n),a=VS("pad",e,t,n),i=VS("kernelSize",e,t,n),o=VS("includeBatchInIndex",e,t,n),{result:u,indexes:l}=r.maxPoolWithArgmax(VS("x",e,t,n),[i[1],i[2]],[s[1],s[2]],a,o);return[u,l]}case"AvgPool3D":{const s=VS("strides",e,t,n),a=VS("pad",e,t,n),i=VS("kernelSize",e,t,n);return[r.avgPool3d(VS("x",e,t,n),[i[1],i[2],i[3]],[s[1],s[2],s[3]],a)]}case"MaxPool3D":{const s=VS("strides",e,t,n),a=VS("pad",e,t,n),i=VS("kernelSize",e,t,n);return[r.maxPool3d(VS("x",e,t,n),[i[1],i[2],i[3]],[s[1],s[2],s[3]],a)]}case"Dilation2D":{const s=VS("strides",e,t,n),a=VS("pad",e,t,n),i=VS("dilations",e,t,n),o=s[1],u=s[2],l=i[1],c=i[2];return[r.dilation2d(VS("x",e,t,n),VS("filter",e,t,n),[o,u],a,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"creation":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"Fill":{const s=VS("shape",e,t,n),a=VS("dtype",e,t,n),i=VS("value",e,t,n);return[r.fill(s,i,a)]}case"LinSpace":{const s=VS("start",e,t,n),a=VS("stop",e,t,n),i=VS("num",e,t,n);return[r.linspace(s,a,i)]}case"Multinomial":{const s=VS("logits",e,t,n),a=VS("numSamples",e,t,n),i=VS("seed",e,t,n);return[r.multinomial(s,a,i)]}case"OneHot":{const s=VS("indices",e,t,n),a=VS("depth",e,t,n),i=VS("onValue",e,t,n),o=VS("offValue",e,t,n),u=VS("dtype",e,t,n);return[r.oneHot(s,a,i,o,u)]}case"Ones":return[r.ones(VS("shape",e,t,n),VS("dtype",e,t,n))];case"OnesLike":return[r.onesLike(VS("x",e,t,n))];case"RandomStandardNormal":return[r.randomStandardNormal(VS("shape",e,t,n),VS("dtype",e,t,n),VS("seed",e,t,n))];case"RandomUniform":return[r.randomUniform(VS("shape",e,t,n),VS("minval",e,t,n),VS("maxval",e,t,n),VS("dtype",e,t,n))];case"RandomUniformInt":return[r.randomUniformInt(VS("shape",e,t,n),VS("minval",e,t,n),VS("maxval",e,t,n),VS("seed",e,t,n))];case"Range":{const s=VS("start",e,t,n),a=VS("stop",e,t,n),i=VS("step",e,t,n);return[r.range(s,a,i,VS("dtype",e,t,n))]}case"TruncatedNormal":{const s=VS("shape",e,t,n),a=VS("mean",e,t,n),i=VS("stdDev",e,t,n),o=VS("seed",e,t,n);return[r.truncatedNormal(s,a,i,VS("dtype",e,t,n),o)]}case"Zeros":return[r.zeros(VS("shape",e,t,n),VS("dtype",e,t,n))];case"ZerosLike":return[r.zerosLike(VS("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"dynamic":return(async(e,t,n,r,s=G)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:r,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:u,softNmsSigma:l}=BT(e,t,n),c=await s.image.nonMaxSuppressionWithScoreAsync(r,a,i,o,u,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:r,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:u}=BT(e,t,n),l=VS("padToMaxOutputSize",e,t,n),c=await s.image.nonMaxSuppressionPaddedAsync(r,a,i,o,u,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:r,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:u}=BT(e,t,n);return[await s.image.nonMaxSuppressionAsync(r,a,i,o,u)]}case"Where":{const r=s.cast(VS("condition",e,t,n),"bool"),a=[await s.whereAsync(r)];return r.dispose(),a}case"ListDiff":return s.setdiff1dAsync(VS("x",e,t,n),VS("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"evaluation":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"LowerBound":{const s=VS("sortedSequence",e,t,n),a=VS("values",e,t,n);return[r.lowerBound(s,a)]}case"TopKV2":{const s=VS("x",e,t,n),a=VS("k",e,t,n),i=VS("sorted",e,t,n),o=r.topk(s,a,i);return[o.values,o.indices]}case"UpperBound":{const s=VS("sortedSequence",e,t,n),a=VS("values",e,t,n);return[r.upperBound(s,a)]}case"Unique":{const s=VS("x",e,t,n),a=r.unique(s);return[a.values,a.indices]}case"UniqueV2":{const s=VS("x",e,t,n),a=VS("axis",e,t,n),i=r.unique(s,a);return[i.values,i.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"image":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"ResizeBilinear":{const s=VS("images",e,t,n),a=VS("size",e,t,n),i=VS("alignCorners",e,t,n),o=VS("halfPixelCenters",e,t,n);return[r.image.resizeBilinear(s,[a[0],a[1]],i,o)]}case"ResizeNearestNeighbor":{const s=VS("images",e,t,n),a=VS("size",e,t,n),i=VS("alignCorners",e,t,n),o=VS("halfPixelCenters",e,t,n);return[r.image.resizeNearestNeighbor(s,[a[0],a[1]],i,o)]}case"CropAndResize":{const s=VS("image",e,t,n),a=VS("boxes",e,t,n),i=VS("boxInd",e,t,n),o=VS("cropSize",e,t,n),u=VS("method",e,t,n),l=VS("extrapolationValue",e,t,n);return[r.image.cropAndResize(s,a,i,o,u,l)]}case"ImageProjectiveTransformV3":{const s=VS("images",e,t,n),a=VS("transforms",e,t,n),i=VS("outputShape",e,t,n),o=VS("fillValue",e,t,n),u=VS("interpolation",e,t,n),l=VS("fillMode",e,t,n);return[r.image.transform(s,a,u.toLowerCase(),l.toLowerCase(),o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"graph":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const s=VS("default",e,t,n);return[GS(e.name,t,n)||s];case"Placeholder":return[GS(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[YS(VS("x",e,t,n))];case"IdentityN":return VS("x",e,t,n).map((e=>YS(e)));case"Shape":return[r.tensor1d(VS("x",e,t,n).shape,"int32")];case"ShapeN":return VS("x",e,t,n).map((e=>r.tensor1d(e.shape)));case"Size":return[r.scalar(VS("x",e,t,n).size,"int32")];case"Rank":return[r.scalar(VS("x",e,t,n).rank,"int32")];case"NoOp":return[r.scalar(1)];case"Print":const a=VS("x",e,t,n),i=VS("data",e,t,n),o=VS("message",e,t,n),u=VS("summarize",e,t,n);WT.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),WT.log(o);for(let e=0;e<i.length;e++)WT.log(Array.prototype.slice.call(i[e].dataSync()).slice(0,u));return[a];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"logical":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"Equal":return[r.equal(VS("a",e,t,n),VS("b",e,t,n))];case"NotEqual":return[r.notEqual(VS("a",e,t,n),VS("b",e,t,n))];case"Greater":return[r.greater(VS("a",e,t,n),VS("b",e,t,n))];case"GreaterEqual":return[r.greaterEqual(VS("a",e,t,n),VS("b",e,t,n))];case"Less":return[r.less(VS("a",e,t,n),VS("b",e,t,n))];case"LessEqual":return[r.lessEqual(VS("a",e,t,n),VS("b",e,t,n))];case"LogicalAnd":return[r.logicalAnd(VS("a",e,t,n),VS("b",e,t,n))];case"LogicalNot":return[r.logicalNot(VS("a",e,t,n))];case"LogicalOr":return[r.logicalOr(VS("a",e,t,n),VS("b",e,t,n))];case"Select":case"SelectV2":return[r.where(VS("condition",e,t,n),VS("a",e,t,n),VS("b",e,t,n))];case"BitwiseAnd":return[r.bitwiseAnd(VS("a",e,t,n),VS("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"matrices":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[r.matMul(VS("a",e,t,n),VS("b",e,t,n),VS("transposeA",e,t,n),VS("transposeB",e,t,n))];case"Einsum":return[r.einsum(VS("equation",e,t,n),...VS("tensors",e,t,n))];case"Transpose":return[r.transpose(VS("x",e,t,n),VS("perm",e,t,n))];case"_FusedMatMul":const[s,a]=VS("fusedOps",e,t,n),i="biasadd"===s,o="prelu"===a,u=VS("numArgs",e,t,n),l=VS("leakyreluAlpha",e,t,n);if(i){if(o&&2!==u)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&1!==u)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[c,h]=VS("args",e,t,n);return[r.fused.matMul({a:VS("a",e,t,n),b:VS("b",e,t,n),transposeA:VS("transposeA",e,t,n),transposeB:VS("transposeB",e,t,n),bias:c,activation:a,preluActivationWeights:h,leakyreluAlpha:l})];case"MatrixBandPart":return[r.linalg.bandPart(VS("a",e,t,n),VS("numLower",e,t,n),VS("numUpper",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"normalization":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"EuclideanNorm":return[r.euclideanNorm(VS("x",e,t,n),VS("axis",e,t,n),VS("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[r.batchNorm(VS("x",e,t,n),VS("mean",e,t,n),VS("variance",e,t,n),VS("offset",e,t,n),VS("scale",e,t,n),VS("epsilon",e,t,n))];case"LRN":return[r.localResponseNormalization(VS("x",e,t,n),VS("radius",e,t,n),VS("bias",e,t,n),VS("alpha",e,t,n),VS("beta",e,t,n))];case"Softmax":return[r.softmax(VS("x",e,t,n))];case"LogSoftmax":return[r.logSoftmax(VS("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"ragged":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:s,outputDenseValues:a}=r.raggedGather(VS("paramsNestedSplits",e,t,n),VS("paramsDenseValues",e,t,n),VS("indices",e,t,n),VS("outputRaggedRank",e,t,n));return s.concat(a)}case"RaggedRange":{const{rtNestedSplits:s,rtDenseValues:a}=r.raggedRange(VS("starts",e,t,n),VS("limits",e,t,n),VS("splits",e,t,n));return[s,a]}case"RaggedTensorToTensor":return[r.raggedTensorToTensor(VS("shape",e,t,n),VS("values",e,t,n),VS("defaultValue",e,t,n),VS("rowPartitionTensors",e,t,n),VS("rowPartitionTypes",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"reduction":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"Max":{const s=VS("axis",e,t,n),a=VS("keepDims",e,t,n);return[r.max(VS("x",e,t,n),s,a)]}case"Mean":{const s=VS("axis",e,t,n),a=VS("keepDims",e,t,n);return[r.mean(VS("x",e,t,n),s,a)]}case"Min":{const s=VS("axis",e,t,n),a=VS("keepDims",e,t,n);return[r.min(VS("x",e,t,n),s,a)]}case"Sum":{const s=VS("axis",e,t,n),a=VS("keepDims",e,t,n);return[r.sum(VS("x",e,t,n),s,a)]}case"All":{const s=VS("axis",e,t,n),a=VS("keepDims",e,t,n);return[r.all(VS("x",e,t,n),s,a)]}case"Any":{const s=VS("axis",e,t,n),a=VS("keepDims",e,t,n);return[r.any(VS("x",e,t,n),s,a)]}case"ArgMax":{const s=VS("axis",e,t,n);return[r.argMax(VS("x",e,t,n),s)]}case"ArgMin":{const s=VS("axis",e,t,n);return[r.argMin(VS("x",e,t,n),s)]}case"Prod":{const s=VS("axis",e,t,n),a=VS("keepDims",e,t,n);return[r.prod(VS("x",e,t,n),s,a)]}case"Cumprod":{const s=VS("axis",e,t,n),a=VS("exclusive",e,t,n),i=VS("reverse",e,t,n);return[r.cumprod(VS("x",e,t,n),s,a,i)]}case"Cumsum":{const s=VS("axis",e,t,n),a=VS("exclusive",e,t,n),i=VS("reverse",e,t,n);return[r.cumsum(VS("x",e,t,n),s,a,i)]}case"Bincount":const s=VS("x",e,t,n),a=VS("weights",e,t,n),i=VS("size",e,t,n);return[r.bincount(s,a,i)];case"DenseBincount":{const s=VS("x",e,t,n),a=VS("weights",e,t,n),i=VS("size",e,t,n),o=VS("binaryOutput",e,t,n);return[r.denseBincount(s,a,i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"slice_join":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"ConcatV2":case"Concat":{const s=VS("n",e,t,n),a=VS("axis",e,t,n);let i=VS("tensors",e,t,n);return i=i.slice(0,s),[r.concat(i,a)]}case"Gather":{const s=VS("x",e,t,n),a=VS("indices",e,t,n);return[r.gather(s,r.cast(a,"int32"),0)]}case"GatherV2":{const s=VS("axis",e,t,n),a=VS("batchDims",e,t,n),i=VS("x",e,t,n),o=VS("indices",e,t,n);return[r.gather(i,r.cast(o,"int32"),s,a)]}case"Reverse":{const s=VS("dims",e,t,n),a=[];for(let e=0;e<s.length;e++)s[e]&&a.push(e);const i=VS("x",e,t,n);return[r.reverse(i,a)]}case"ReverseV2":{const s=VS("axis",e,t,n),a=VS("x",e,t,n);return[r.reverse(a,s)]}case"Slice":{const s=VS("begin",e,t,n),a=VS("size",e,t,n);return[r.slice(VS("x",e,t,n),s,a)]}case"StridedSlice":{const s=VS("begin",e,t,n),a=VS("end",e,t,n),i=VS("strides",e,t,n),o=VS("beginMask",e,t,n),u=VS("endMask",e,t,n),l=VS("ellipsisMask",e,t,n),c=VS("newAxisMask",e,t,n),h=VS("shrinkAxisMask",e,t,n),p=VS("x",e,t,n);return[r.stridedSlice(p,s,a,i,o,u,l,c,h)]}case"Pack":return wi((()=>{const s=VS("axis",e,t,n),a=VS("tensors",e,t,n),i=a[0].shape,o=r.squeeze(a[0]).shape,u=a.map((e=>{const t=pe(e.shape,i);if(!t&&!pe(r.squeeze(e).shape,o))throw new Error("the input tensors shape does not match");return t?e:r.reshape(e,i)}));return[r.stack(u,s)]}));case"Unpack":{const s=VS("axis",e,t,n),a=VS("tensor",e,t,n);return r.unstack(a,s)}case"Tile":{const s=VS("reps",e,t,n);return[r.tile(VS("x",e,t,n),s)]}case"Split":case"SplitV":{const s=VS("axis",e,t,n),a=VS("numOrSizeSplits",e,t,n),i=VS("x",e,t,n);return r.split(i,a,s)}case"ScatterNd":{const s=VS("indices",e,t,n),a=VS("values",e,t,n),i=VS("shape",e,t,n);return[r.scatterND(s,a,i)]}case"GatherNd":{const s=VS("x",e,t,n),a=VS("indices",e,t,n);return[r.gatherND(s,a)]}case"SparseToDense":{const s=VS("sparseIndices",e,t,n),a=VS("outputShape",e,t,n),i=VS("sparseValues",e,t,n),o=VS("defaultValue",e,t,n);return[r.sparseToDense(s,i,a,i.dtype===o.dtype?o:r.cast(o,i.dtype))]}case"TensorScatterUpdate":{const s=VS("indices",e,t,n),a=VS("values",e,t,n),i=VS("tensor",e,t,n);return[r.tensorScatterUpdate(i,s,a)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"sparse":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:s,outputValues:a,emptyRowIndicator:i,reverseIndexMap:o}=r.sparse.sparseFillEmptyRows(VS("indices",e,t,n),VS("values",e,t,n),VS("denseShape",e,t,n),VS("defaultValue",e,t,n));return[s,a,i,o]}case"SparseReshape":{const{outputIndices:s,outputShape:a}=r.sparse.sparseReshape(VS("inputIndices",e,t,n),VS("inputShape",e,t,n),VS("newShape",e,t,n));return[s,a]}case"SparseSegmentMean":return[r.sparse.sparseSegmentMean(VS("data",e,t,n),VS("indices",e,t,n),VS("segmentIds",e,t,n))];case"SparseSegmentSum":return[r.sparse.sparseSegmentSum(VS("data",e,t,n),VS("indices",e,t,n),VS("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"spectral":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"FFT":return[r.fft(VS("x",e,t,n))];case"IFFT":return[r.ifft(VS("x",e,t,n))];case"RFFT":return[r.rfft(VS("x",e,t,n))];case"IRFFT":return[r.irfft(VS("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"string":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"StaticRegexReplace":return[r.string.staticRegexReplace(VS("input",e,t,n),VS("pattern",e,t,n),VS("rewrite",e,t,n),VS("replaceGlobal",e,t,n))];case"StringNGrams":{const{nGrams:s,nGramsSplits:a}=r.string.stringNGrams(VS("data",e,t,n),VS("dataSplits",e,t,n),VS("separator",e,t,n),VS("nGramWidths",e,t,n),VS("leftPad",e,t,n),VS("rightPad",e,t,n),VS("padWidth",e,t,n),VS("preserveShortSequences",e,t,n));return[s,a]}case"StringSplit":{const{indices:s,values:a,shape:i}=r.string.stringSplit(VS("input",e,t,n),VS("delimiter",e,t,n),VS("skipEmpty",e,t,n));return[s,a,i]}case"StringToHashBucketFast":return[r.string.stringToHashBucketFast(VS("input",e,t,n),VS("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"transformation":return s((()=>((e,t,n,r=G)=>{switch(e.op){case"Cast":return[r.cast(VS("x",e,t,n),VS("dtype",e,t,n))];case"ExpandDims":{const s=VS("axis",e,t,n);return[r.expandDims(VS("x",e,t,n),s)]}case"Squeeze":{const s=VS("axis",e,t,n);return[r.squeeze(VS("x",e,t,n),s)]}case"Reshape":return[r.reshape(VS("x",e,t,n),VS("shape",e,t,n))];case"EnsureShape":return[r.ensureShape(VS("x",e,t,n),VS("shape",e,t,n))];case"MirrorPad":return[r.mirrorPad(VS("x",e,t,n),VS("padding",e,t,n),VS("mode",e,t,n))];case"PadV2":case"Pad":return[r.pad(VS("x",e,t,n),VS("padding",e,t,n),VS("constantValue",e,t,n))];case"SpaceToBatchND":{const s=VS("blockShape",e,t,n),a=VS("paddings",e,t,n);return[r.spaceToBatchND(VS("x",e,t,n),s,a)]}case"BatchToSpaceND":{const s=VS("blockShape",e,t,n),a=VS("crops",e,t,n);return[r.batchToSpaceND(VS("x",e,t,n),s,a)]}case"DepthToSpace":{const s=VS("blockSize",e,t,n),a=VS("dataFormat",e,t,n).toUpperCase();return[r.depthToSpace(VS("x",e,t,n),s,a)]}case"BroadcastTo":return[r.broadcastTo(VS("x",e,t,n),VS("shape",e,t,n))];case"BroadcastArgs":return[r.broadcastArgs(VS("s0",e,t,n),VS("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"hash_table":return(async(e,t,n,r)=>{switch(e.op){case"HashTable":case"HashTableV2":{const s=r.getHashTableHandleByName(e.name);if(null!=s)return[s];{const s=VS("keyDType",e,t,n),a=VS("valueDType",e,t,n),i=new UT(s,a);return r.addHashTable(e.name,i),[i.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const s=VS("tableHandle",e,t,n,r),a=VS("keys",e,t,n),i=VS("values",e,t,n),o=r.getHashTableById(s.id);return[await o.import(a,i)]}case"LookupTableFind":case"LookupTableFindV2":{const s=VS("tableHandle",e,t,n,r),a=VS("keys",e,t,n),i=VS("defaultValue",e,t,n),o=r.getHashTableById(s.id);return[await o.find(a,i)]}case"LookupTableSize":case"LookupTableSizeV2":{const s=VS("tableHandle",e,t,n,r);return[r.getHashTableById(s.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n,r);case"custom":const a=WS(e.op);if(a&&a.customExecutor)return a.customExecutor(new OT(e,t,n));throw TypeError(`Custom op ${e.op} is not registered.`);default:throw TypeError(`Unknown op '${e.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return je(a)?a.then((e=>[].concat(e))):[].concat(a)}class GT{constructor(e={},t={},n={},r={},s){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=r,this.parseNodeNameCache=s,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;t<this.contexts.length-1;t++){const n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map((e=>0===e.id&&0===e.iterationId?"":`${e.frameName}-${e.iterationId}`)).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()}nextIteration(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");{this.contexts=this.contexts.slice(),this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}function jT(e,t,n,r){const s=new Set,a=[];let i=null,o=null;const u=new Set,l=new Set(Object.keys(e).map((e=>KS(e)[0])));r=r||[];const c=new Set(r.map((e=>KS(e.name)[0]))),h=[...t];for(;h.length>0;){const e=h.pop();(YT(e)||JT(e)||ZT(e))&&null==i&&(i=e,o=i.children.map((e=>e.name)).filter((e=>s.has(e)))),s.add(e.name),null==n[e.name]&&(l.has(e.name)||c.has(e.name)||(0!==e.inputs.length?e.inputs.forEach((e=>{u.has(e.name)||(u.add(e.name),h.push(e))})):a.push(e.name)))}return{inputs:e,outputs:t,usedNodes:s,missingInputs:a,dynamicNode:i,syncInputs:o}}class HT extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}const qT=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),KT=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),XT=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function YT(e){return qT.has(e.op)}function JT(e){return KT.has(e.op)}function ZT(e){return XT.has(e.op)}var QT=n(96763);class eC{get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map((t=>e[t].map((e=>e.id))));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map((e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0})))}get outputs(){return this._outputs.map((e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0})))}get inputNodes(){return this._inputs.map((e=>e.signatureKey||e.name))}get outputNodes(){return this._outputs.map((e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t}))}get functions(){return Object.keys(this._functions).reduce(((e,t)=>(e[t]=this._functions[t].signature,e)),{})}constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this.parseNodeNameCache=new Map,this._weightMap={},this.SEPARATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,null!=e.functions&&Object.keys(e.functions).forEach((t=>{this._functionExecutorMap[t]=new eC(e.functions[t],this)}))}getCompilationKey(e,t){const n=e.map((e=>e.name)).sort(),r=t.map((e=>e.name)).sort();return n.join(this.SEPARATOR)+"--"+r.join(this.SEPARATOR)}compile(e,t){const n=jT(e,t,this.weightMap,this._initNodes),{missingInputs:r,dynamicNode:s,syncInputs:a}=n;if(null!=s)throw new Error(`This execution contains the node '${s.name}', which has the dynamic op '${s.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);if(r.length>0){const n=t.map((e=>e.name)),s=Object.keys(e);throw new Error(`Cannot compute the outputs [${n}] from the provided inputs [${s}]. Missing the following inputs: [${r}]`)}const i=function(e,t){const{usedNodes:n,inputs:r}=t,s=Object.keys(r).map((e=>KS(e)[0])).map((t=>e.nodes[t])),a=e.initNodes||[],i=e=>n.has("string"==typeof e?e:e.name);function o(e){return[...new Map(e.map((e=>[e.name,e]))).values()]}const u=o([...s,...e.weights,...a]).filter(i),l=o([...u,...Object.values(e.nodes)]).filter(i),c=new Map(l.map((e=>[e.name,e]))),h={};for(const e of l){h[e.name]=h[e.name]||0;for(const t of e.children)i(t)||(h[t.name]=Number.POSITIVE_INFINITY),h[t.name]=(h[t.name]||0)+1}const p=Object.entries(h).filter((([,e])=>0===e)).map((([e])=>e)),d=[...p];for(;p.length>0;){const e=p.pop(),t=c.get(e);for(const e of t.children.filter(i))0==--h[e.name]&&(d.push(e.name),p.push(e.name))}const f=function(e,t){const n=new Map(e.map((e=>[e.name,e]))),r=t.map((e=>e.name)),s=new Set(r);for(;r.length>0;){const e=r.pop(),t=n.get(e);for(const e of t.children)n.has(e.name)&&!s.has(e.name)&&(s.add(e.name),r.push(e.name))}return e.filter((e=>s.has(e.name)))}(d.map((e=>c.get(e))),u);return function(e,t){const n=new Map(e.map(((e,t)=>[e.name,t]))),r=new Set(t.map((e=>e.name))),s=e=>r.has("string"==typeof e?e:e.name),a=new Set(e.map((e=>e.name))),i=e=>a.has("string"==typeof e?e:e.name);for(const t of e){for(const e of t.children.filter(i)){if(!n.has(e.name))throw new HT(`Child ${e.name} of node ${t.name} is unreachable.`);if(n.get(t.name)>n.get(e.name))throw new HT(`Node ${t.name} is scheduled to run after its child ${e.name}.`)}if(!s(t))for(const e of t.inputs){if(!n.has(e.name))throw new HT(`Input ${e.name} of node ${t.name} is unreachable.`);if(n.get(e.name)>n.get(t.name))throw new HT(`Node ${t.name} is scheduled to run before its input ${e.name}.`)}}}(f,u),f}(this.graph,n),o=function(e){const t=new Map(e.map(((e,t)=>[e.name,t]))),n=Number.MAX_SAFE_INTEGER,r=e.map(((e,t)=>YT(e)?n:t)),s=e=>{const n=r[t.get(e.name)];return null==n?-1:n},a=e.map(((e,t)=>e.children.map(s).reduce(((e,t)=>Math.max(e,t)),r[t]))),i=new Map;for(let t=0;t<e.length;++t){const r=a[t];if(r===n)continue;const s=e[t],o=e[r];i.has(o.name)||i.set(o.name,[]),i.get(o.name).push(s)}return i}(i);return{orderedNodes:i,nodeLiveUntilMap:o}}cloneAndKeepTensor(e){if(null==e)return null;const t=e.clone();return ki(t),t}cloneTensorList(e){if(!e)return null;const t=e.map((e=>this.cloneAndKeepTensor(e)));return t}cloneTensorMap(e){return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,this.cloneTensorList(t)])))}execute(e,t){this.disposeIntermediateTensors(),e=this.mapInputs(e);const n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const r=n.map((e=>this.graph.nodes[KS(e)[0]])),s=t.map((e=>KS(e)[0])),a=new Set(s);let i=s.map((e=>this.graph.nodes[e]));0===i.length&&(i=this._outputs);const o=this.getCompilationKey(r,i);let u=this.compiledMap.get(o);null==u&&(u=this.compile(e,i),this.compiledMap.set(o,u));try{this.keepIntermediateTensors=Ye().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,QT.warn(e.message)}const l={},c={};return wi((()=>{const n=new GT(this.weightMap,l,c,this.functionExecutorMap,this.parseNodeNameCache),r=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach((t=>{const[s,a]=KS(t,n),i=[];i[a]=e[t],r[s]=i,this.keepIntermediateTensors&&(this.clonedTensorsMap[s]=this.cloneTensorList(i))}));const s=this.getFrozenTensorIds(r),{orderedNodes:i,nodeLiveUntilMap:o}=u;for(const e of i){if(r[e.name])continue;const t=VT(e,r,n,this._resourceManager);if(je(t))throw new Error(`The execution of the op '${e.op}' returned a promise. Please use model.executeAsync() instead.`);r[e.name]=t,this.keepIntermediateTensors&&(this.clonedTensorsMap[e.name]=this.cloneTensorList(t)),this.checkTensorForDisposalWithNodeLiveUntilInfo(e,r,n,s,a,o.get(e.name))}return null==this.parent&&n.dispose(s),t.map((e=>GS(e,r,n)))}))}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map((t=>e[t])).map((e=>e.map((e=>e.id)))));return new Set(t)}checkTensorForDisposal(e,t,n,r,s,a,i){if(!YT(t)&&!a.has(e)){for(const r of n[e])null!=r&&(i[r.id]=(i[r.id]||0)+t.children.length);for(const e of t.inputs){if(YT(e))continue;const t=jS(e.name,n,r);if(null!=t)for(const e of t){if(!e||e.kept||s.has(e.id))continue;const t=i[e.id];1===t?(e.dispose(),delete i[e.id]):null!=t&&i[e.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,n,r,s,a){function i(e){return YT(e)||s.has(e.name)}if(!YT(e)&&null!=a)for(const e of a){if(i(e))continue;const s=jS(e.name,t,n);for(const e of s)!e||e.kept||r.has(e.id)||e.dispose()}}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach((e=>{for(const t of e)t&&!t.isDisposed&&t.dispose()})),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(e,t,n=!1,r={},s={}){this.disposeIntermediateTensors(),n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepIntermediateTensors=Ye().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,QT.warn(e.message)}const a=new GT(this.weightMap,r,s,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const i=await this.executeWithControlFlow(e,a,t,n),o=t.map((e=>GS(e,i,a))),u=o.map((e=>e.id)),l=Object.keys(e).map((t=>e[t].id)),c=new Set([...u,...l,...this.weightIds]);return Object.values(i).forEach((e=>{e.forEach((e=>{!e||e.isDisposed||c.has(e.id)||e.dispose()}))})),null==this.parent&&a.dispose(c),o}async executeFunctionAsync(e,t,n){const r=e.reduce(((e,t,n)=>(e[this.inputs[n].name]=t,e)),{});return this._executeAsync(r,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,r){const s=Object.keys(e),a=s.map((e=>this.graph.nodes[KS(e)[0]])),i=n.map((e=>KS(e)[0])),o=new Set(i);let u=i.map((e=>this.graph.nodes[e]));0===u.length&&(u=this._outputs);const{usedNodes:l,missingInputs:c,dynamicNode:h,syncInputs:p}=jT(e,u,this.weightMap,this._initNodes),d=[...a,...this.graph.weights,...this._initNodes||[]].map((e=>({node:e,contexts:t.currentContext}))),f=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,r]=KS(t),s=[];s[r]=e[t],f[n]=s}));const m={},g=this.getFrozenTensorIds(f),y={};for(;d.length>0;){const e=this.processStack(a,d,t,f,y,g,o,m,l);await Promise.all(e)}null!=h||r||QT.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const b=u.filter((e=>!YT(e)&&!GS(e.name,f,t))).map((e=>e.name));if(b.length>0){let e="";throw null!=h&&(e=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${p}]`),new Error(`Cannot compute the outputs [${b}] from the provided inputs [${s}]. Consider providing the following inputs: [${c}]. ${e}`)}return f}processStack(e,t,n,r,s,a,i,o,u){const l=[];for(;t.length>0;){const e=t.pop();n.currentContext=e.contexts;let c="";if("Enter"===e.node.op&&VS("isConstant",e.node,r,n)&&([c]=HS(e.node.name,n)),null==r[e.node.name]){const h=VT(e.node,r,n,this._resourceManager);c||([c]=HS(e.node.name,n));const p=n.currentContext;je(h)?l.push(h.then((l=>(r[c]=l,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(l)),n.currentContext=p,this.checkTensorForDisposal(c,e.node,r,n,a,i,o),this.processChildNodes(e.node,t,n,r,s,u),l)))):(r[c]=h,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(h)),this.checkTensorForDisposal(c,e.node,r,n,a,i,o),this.processChildNodes(e.node,t,n,r,s,u))}else this.processChildNodes(e.node,t,n,r,s,u)}return l}processChildNodes(e,t,n,r,s,a){e.children.forEach((e=>{const[i]=HS(e.name,n);!s[i]&&a.has(e.name)&&("Merge"===e.op?e.inputNames.some((e=>!!GS(e,r,n)))&&(s[i]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every((e=>!!GS(e,r,n)))&&(s[i]=!0,t.push({contexts:n.currentContext,node:e})))}))}dispose(){Object.keys(this.weightMap).forEach((e=>this.weightMap[e].forEach((e=>e.dispose()))))}checkInputShapeAndType(e){Object.keys(e).forEach((t=>{const n=e[t],[r]=KS(t),s=this.graph.nodes[r];if(s.attrParams.shape&&s.attrParams.shape.value){const e=s.attrParams.shape.value;ie(e.length===n.shape.length&&n.shape.every(((t,n)=>-1===e[n]||e[n]===t)),(()=>`The shape of dict['${s.name}'] provided in model.execute(dict) must be [${e}], but was [${n.shape}]`))}s.attrParams.dtype&&s.attrParams.dtype.value&&ie(n.dtype===s.attrParams.dtype.value,(()=>`The dtype of dict['${s.name}'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${n.dtype}`))}))}mapInputs(e){var t,n;const r={};for(const s in e){const a=null===(n=null===(t=this._signature)||void 0===t?void 0:t.inputs)||void 0===n?void 0:n[s];null!=a?r[a.name]=e[s]:r[s]=e[s]}return r}checkInputs(e){const t=Object.keys(e).filter((e=>{const[t]=KS(e);return null==this.graph.nodes[t]}));if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map((e=>{var t,n;const r=null===(n=null===(t=this._signature)||void 0===t?void 0:t.outputs)||void 0===n?void 0:n[e];return null!=r?r.name:e}),{})}checkOutputs(e){e.forEach((e=>{const[t]=KS(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)}))}}class tC{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(const e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(const e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}}const nC="?tfjs-format=file",rC="model.json";class sC{get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}get modelStructuredOutputKeys(){return this.structuredOutputKeys}constructor(e,t={},n=u){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,null==t&&(this.loadOptions={}),this.resourceManager=new tC}findIOHandler(){const e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{const t=this.io.getLoadHandlers(e,this.loadOptions);if(0===t.length)t.push(this.io.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}load(){if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const e=this.handler.load();return je(e)?e.then((e=>null==e.getWeightStream?this.loadSync(e):this.loadStreaming(e))):this.loadSync(e)}loadSync(e){const t=this.io.decodeWeights(e.weightData,e.weightSpecs);return this.loadWithWeightMap(e,t)}async loadStreaming(e){if(null==e.getWeightStream)throw new Error("Model artifacts missing streamWeights function");const t=await Wi(e.getWeightStream(),e.weightSpecs);return this.loadWithWeightMap(e,t)}loadWithWeightMap(e,t){this.artifacts=e;const n=this.artifacts.modelTopology;let r=this.artifacts.signature;if(null!=this.artifacts.userDefinedMetadata){const e=this.artifacts.userDefinedMetadata;null!=e.signature&&(r=e.signature),null!=e.structuredOutputKeys&&(this.structuredOutputKeys=e.structuredOutputKeys)}if(this.signature=r,this.version=`${n.versions.producer}.${n.versions.minConsumer}`,this.executor=new eC(yT.Instance.transformGraph(n,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(t),this.executor.resourceManager=this.resourceManager,null!=e.modelInitializer&&null!=e.modelInitializer.node){const t=yT.Instance.transformGraph(e.modelInitializer);this.initializer=new eC(t),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if("string"==typeof e){const t=this.io.getSaveHandlers(e);if(0===t.length)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Error(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}addStructuredOutputNames(e){if(this.structuredOutputKeys){const t={};return(e instanceof wa?[e]:e).forEach(((e,n)=>t[this.structuredOutputKeys[n]]=e)),t}return e}predict(e,t){const n=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(n)}async predictAsync(e,t){const n=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(n)}normalizeInputs(e){var t;if(!(e instanceof wa||Array.isArray(e))){const n=null===(t=this.signature)||void 0===t?void 0:t.inputs;if(null!=n)for(const t in n){const r=n[t];null!=r.resourceId&&(e[t]=this.resourceIdToCapturedInput[r.resourceId])}return e}e=Array.isArray(e)?e:[e];const n=Object.keys(this.resourceIdToCapturedInput).length;if(e.length+n!==this.inputNodes.length)throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length-n} non-resource placeholders, while there are ${e.length} input tensors provided.`);let r=0;return this.inputNodes.reduce(((t,n)=>{var s,a,i;const o=null===(i=null===(a=null===(s=this.signature)||void 0===s?void 0:s.inputs)||void 0===a?void 0:a[n])||void 0===i?void 0:i.resourceId;return t[n]=null!=o?this.resourceIdToCapturedInput[o]:e[r++],t}),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}executeInitializerGraph(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){const t=this.initializerSignature.outputs,n=Object.keys(t);for(let r=0;r<n.length;r++){const s=t[n[r]];this.resourceIdToCapturedInput[s.resourceId]=e[r]}}}execute(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(this.executeInitializerGraph()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce(((t,n)=>(t[n]=[e[n]],t)),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&vi(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}async function aC(e,t={},n=u){if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");null==t&&(t={}),t.fromTFHub&&"string"==typeof e&&(e=function(e){return e.endsWith("/")||(e+="/"),`${e}${rC}${nC}`}(e));const r=new sC(e,t,n);return await r.load(),r}function iC(e){if(null==e)throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide model artifacts or an IOHandler that loads the model");let t;if(e instanceof Array){const[n,r]=e;if(!n)throw new Error("modelJSON must be the first element of the array");if(!(r&&r instanceof ArrayBuffer))throw new Error("An ArrayBuffer of weights must be the second element of the array");if(!("modelTopology"in n))throw new Error("Model JSON is missing 'modelTopology'");if(!("weightsManifest"in n))throw new Error("Model JSON is missing 'weightsManifest'");t=Vu(Ki(n,Ji(n.weightsManifest),r))}else if("load"in e)t=e;else{if(!("modelTopology"in e&&"weightSpecs"in e&&"weightData"in e))throw new Error("Unknown model format");t=Vu(e)}const n=new sC(t);return n.load(),n}const oC="4.20.0";function uC(e,t,n=new Map,r=new Set){if(null==e)return null;if("function"==typeof Blob&&e instanceof Blob)return e.slice();if(r.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);const s=t(e);if(s.recurse&&null!==s.value)throw new Error("A deep map function may not return both a value and recurse=true.");if(s.recurse){if(dC(e)){const s=Array.isArray(e)?[]:{};r.add(e);for(const a in e){const i=uC(e[a],t,n,r);s[a]=i}return r.delete(e),e.__proto__&&(s.__proto__=e.__proto__),s}throw new Error(`Can't recurse into non-iterable type: ${e}`)}return n.set(e,s.value),s.value}function lC(e,t=hC){return cC(e,t)}function cC(e,t,n=new Set){const r=e[0];if(n.has(r))throw new Error("Circular references are not supported.");const s=t(e);if(s.recurse&&null!==s.value)throw new Error("A deep zip function may not return both a value and recurse=true.");if(s.recurse){if(dC(r)){const s=Array.isArray(r)?[]:{};n.add(r);for(const a in r){const r=cC(e.map((e=>e[a])),t,n);s[a]=r}return n.delete(r),s}throw new Error(`Can't recurse into non-iterable type: ${r}`)}return s.value}function hC(e){return null===e?null:dC(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function pC(e,t){const n=new Map;uC(e,t,n);for(const e of Array.from(n.keys())){const t=n.get(e);if(je(t)){const r=await t;n.set(e,r)}}return uC(e,t,n)}function dC(e){let t=!1;if(Ye().get("IS_BROWSER"))t=e instanceof TextDecoder;else{const{StringDecoder:r}=n(80551);t=e instanceof r}return null!=e&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||"object"==typeof e&&!(e instanceof wa)&&!(e instanceof Promise)&&!t)}function fC(e){return e instanceof wa?{value:e.clone(),recurse:!1}:dC(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class mC{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,null==e)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return 0===this.length()}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(const t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);const e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}}class gC extends mC{constructor(){super(gC.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){const e=2*this.capacity,t=new Array(e),n=this.length();for(let e=0;e<n;e++)t[e]=this.get(this.wrap(this.begin+e));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}}function yC(e){return new wC(e)}function bC(e){return new vC(e)}gC.INITIAL_CAPACITY=32;class xC{async toArray(){const e=[];let t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){const e=this.prefetch(100),t=[];let n=await e.next();for(;!n.done;)t.push(n.value),n=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),n=e(t.value);for(;!t.done&&n;)t=await this.next(),n=e(t.value)}handleErrors(e){return new $C(this,e)}filter(e){return new TC(this,e)}map(e){return new CC(this,e)}mapAsync(e){return new EC(this,e)}serialMapAsync(e){return new EC(this,e).serial()}flatmap(e){return new RC(this,e)}async forEachAsync(e){return this.map(e).resolveFully()}async serialForEach(e){return this.serialMapAsync(e).resolveWhile((e=>!0===e))}rowMajorBatch(e,t=!0){return new SC(this,e,t)}columnMajorBatch(e,t=!0,n=hC){return this.rowMajorBatch(e,t).map((e=>lC(e,n)))}concatenate(e,t){return new OC(yC([this,e]),t)}take(e){return e<0||null==e?this:new NC(this,e)}skip(e){return e<0||null==e?this:new IC(this,e)}prefetch(e){return new DC(this,e)}shuffle(e,t){return new MC(this,e,t)}serial(){return new kC(this)}}class wC extends xC{constructor(e){super(),this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};const e=this.items[this.trav];return this.trav++,{value:(t=e,function(e,t){return uC(e,t)}(t,fC)),done:!1};var t}}class vC extends xC{constructor(e){super(),this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}}class kC extends xC{constructor(e){super(),this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){return this.upstream.next()}}class IC extends xC{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){const e=await this.upstream.next();if(e.done)return e;vi(e.value)}return this.upstream.next()}}class NC extends xC{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}}class SC extends xC{constructor(e,t,n=!0){super(),this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){const e=[];for(;e.length<this.batchSize;){const t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}}class TC extends xC{constructor(e,t){super(),this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;;){const e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;vi(e.value)}}}class CC extends xC{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=Ma(e.value),n=this.transform(e.value),r=Ma(n);for(const e of t)Da(e,r)||e.dispose();return{value:n,done:!1}}}class $C extends xC{constructor(e,t){super(),this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}}class EC extends xC{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=Ma(e.value),n=await this.transform(e.value),r=Ma(n);for(const e of t)Da(e,r)||e.dispose();return{value:n,done:!1}}}class AC extends xC{constructor(){super(),this.outputQueue=new gC,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;0===this.outputQueue.length();)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}}class RC extends AC{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){const e=await this.upstream.next();if(e.done)return!1;const t=Ma(e.value),n=this.transform(e.value),r=Ma(n);this.outputQueue.pushAll(n);for(const e of t)Da(e,r)||e.dispose();return!0}}class OC extends xC{constructor(e,t){super(),this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,null==this.iterator){const e=await this.moreIterators.next();if(e.done)return{value:null,done:!0};this.iterator=e.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}const t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}}var FC;!function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"}(FC||(FC={}));class _C extends xC{constructor(e,t=FC.FAIL){super(),this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,n=0;const r=await pC(this.iterators,(function(e){return e instanceof xC?{value:e.next().then((e=>(t++,e.done&&n++,e.value))),recurse:!1}:{value:null,recurse:!0}}));if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case FC.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case FC.SHORTEST:return{value:null,done:!0};case FC.LONGEST:}return this.count++,{value:r,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class DC extends xC{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new mC(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){const e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}}class MC extends DC{constructor(e,t,n){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=Fp.alea(n||Zs().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){const e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(!t.done)return this.refill(),t;this.upstreamExhausted=!0}return{value:null,done:!0}}}class LC{constructor(){this.size=null}batch(e,t=!0){const n=this;let r;return ie(e>0,(()=>`batchSize needs to be positive, but it is\n ${e}`)),r=this.size===1/0||null==this.size?this.size:t?Math.ceil(this.size/e):Math.floor(this.size/e),zC((async()=>(await n.iterator()).columnMajorBatch(e,t,WC)),r)}concatenate(e){const t=this;let n;return n=this.size===1/0||e.size===1/0?1/0:null!=this.size&&null!=e.size?this.size+e.size:null,zC((async()=>(await t.iterator()).concatenate(await e.iterator())),n)}filter(e){const t=this;let n;return n=this.size===1/0?1/0:null,zC((async()=>(await t.iterator()).filter((t=>wi((()=>e(t)))))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return zC((async()=>(await t.iterator()).map((t=>wi((()=>e(t)))))),this.size)}mapAsync(e){const t=this;return zC((async()=>(await t.iterator()).mapAsync(e)),this.size)}prefetch(e){if(null==e)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");const t=this;return zC((async()=>(await t.iterator()).prefetch(e)),this.size)}repeat(e){const t=this;let n;return n=null!=this.size&&e>0?this.size*e:0===e?0:null!=this.size&&(void 0===e||e<0)?1/0:null,zC((async()=>{return n=bC((async()=>({value:await t.iterator(),done:!1}))).take(e),new OC(n,r);var n,r}),n)}skip(e){const t=this;let n;return n=null!=this.size&&e>=0&&this.size>=e?this.size-e:null!=this.size&&(this.size<e||void 0===e||e<0)?0:null,zC((async()=>(await t.iterator()).skip(e)),n)}shuffle(e,t,n=!0){if(null==e||e<0)throw null==this.size?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);const r=this,s=Fp.alea(t||Zs().toString());return zC((async()=>{let t=s.int32();return n&&(t+=s.int32()),(await r.iterator()).shuffle(e,t.toString())}),this.size)}take(e){const t=this;let n;return n=null!=this.size&&this.size>e?e:null!=this.size&&this.size<=e?this.size:null,zC((async()=>(await t.iterator()).take(e)),n)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}}function zC(e,t=null){return new class extends LC{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function PC(e){return zC((async()=>yC(e)),e.length)}function BC(e){if(!dC(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n<e.length;n++)t=null==t?e[n].size:Math.min(t,e[n].size);else if(e instanceof Object)for(const n in e)t=null==t?e[n].size:Math.min(t,e[n].size);return zC((async()=>function(e,t=FC.FAIL){return new _C(e,t)}(await pC(e,(e=>{if(e instanceof LC)return{value:e.iterator(),recurse:!1};if(dC(e))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")})),FC.SHORTEST)),t)}function WC(e){if(null===e)return null;return null==(t=e[0])||null===(n=t)||"object"!=typeof n&&"function"!=typeof n||Array.isArray(t)||"object"==typeof t&&t instanceof wa||na(t)?{value:function(e){if(0===e.length)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof wa?yd(e):ui(e)}(e),recurse:!1}:{value:null,recurse:!0};var t,n}LC.MAX_BUFFER_SIZE=1e4;class UC extends LC{constructor(e){super(),this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split("\n").map((e=>(e.endsWith("\r")&&(e=e.slice(0,-1)),e)))}}const VC='"',GC=Symbol("out"),jC=Symbol("field"),HC=Symbol("quote"),qC=Symbol("quoteafterquote"),KC=Symbol("quoteinquote");class XC extends LC{async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&ie(e.length===this.fullColumnNames.length,(()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+").")),this.fullColumnNames||(this.fullColumnNames=e);const t=this.fullColumnNames.reduce(((e,t)=>(e[t]=e[t]+1||1,e)),{}),n=Object.keys(t).filter((e=>t[e]>1));if(ie(0===n.length,(()=>"Duplicate column names found: "+n.toString())),this.columnConfigs)for(const e of Object.keys(this.columnConfigs))if(-1===this.fullColumnNames.indexOf(e))throw new Error('The key "'+e+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").");this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){const e=await this.base.iterator(),t=await e.next();if(t.done)throw new Error("No data was found for CSV parsing.");const n=t.value;return this.parseRow(n,!1)}return null}constructor(e,t){super(),this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new UC(e),t||(t={}),this.hasHeader=!1!==t.hasHeader,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(ie(null==t.delimiter,(()=>"Delimiter should not be provided when delimWhitespace is true.")),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map((e=>this.makeDataElement(e)))}makeDataElement(e){const t=this.parseRow(e),n={},r={};for(let s=0;s<this.fullColumnNames.length;s++){const a=this.fullColumnNames[s],i=this.columnConfigs?this.columnConfigs[a]:null;if(!this.configuredColumnsOnly||i){const o=t[s];let u=null;if(""===o)if(i&&void 0!==i.default)u=i.default;else{if(i&&(i.required||i.isLabel))throw new Error(`Required column ${a} is empty in this line: ${e}`);u=void 0}else{const e=Number(o);if(isNaN(e))u=i&&"bool"===i.dtype?this.getBoolean(o):o;else if(i&&i.dtype)switch(i.dtype){case"float32":default:u=e;break;case"int32":u=Math.floor(e);break;case"bool":u=this.getBoolean(o)}else u=e}i&&i.isLabel?r[a]=u:n[a]=u}}return 0===Object.keys(r).length?n:{xs:n,ys:r}}getBoolean(e){return"1"===e||"true"===e.toLowerCase()?1:0}parseRow(e,t=!0){const n=[];let r=0;const s=e.length;let a=GC;for(let t=0;t<s;t++)switch(a){case GC:switch(e.charAt(t)){case VC:r=t+1,a=HC;break;case this.delimiter:if(r=t+1," "===this.delimiter&&this.delimWhitespace)break;n.push(""),a=GC;break;default:a=jC,r=t}break;case jC:e.charAt(t)===this.delimiter&&(n.push(e.substring(r,t)),a=GC,r=t+1);break;case HC:e.charAt(t)===VC&&(a=qC);break;case qC:switch(e.charAt(t)){case this.delimiter:n.push(e.substring(r,t-1)),a=GC,r=t+1;break;case VC:a=HC;break;default:a=KC}break;case KC:e.charAt(t)===VC&&(a=HC)}if(a===qC?n.push(e.substring(r,s-1)):n.push(e.substring(r)),t&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}}class YC extends xC{constructor(e){super(),this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;const t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=!1!==e.includeSpectrogram,this.includeWaveform=!0===e.includeWaveform,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(!Ye().get("IS_BROWSER"))throw new Error("microphone API is only supported in browser environment.");const t=new YC(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:null==this.audioTrackConstraints||this.audioTrackConstraints,video:!1})}catch(e){throw new Error(`Error thrown while initializing video stream: ${e.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");const e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,this.sampleRateHz){if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`)}else this.sampleRateHz=this.audioContext.sampleRate;const t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2*this.fftSize,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t;const n=await this.getAudioData();if(this.includeSpectrogram){const t=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(t,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){const e=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(e,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){const e=[],t=[];let n=0;return new Promise((r=>{const s=setInterval((()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&r({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(s),r({freqDataQueue:e,timeDataQueue:t}))}),this.fftSize/this.sampleRateHz*1e3)}))}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),null!=this.stream&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){const t=e[0].length,n=new Float32Array(e.length*t);return e.forEach(((e,r)=>n.set(e,r*t))),n}getTensorFromAudioDataArray(e,t){const n=new Float32Array(le(t));return n.set(e,n.length-e.length),ui(n,t)}}var JC=n(96763);class ZC extends xC{constructor(e,t){if(super(),this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=vd([0],"int32"),this.webcamConfig.centerCrop){const e=1*this.webcamConfig.resizeWidth/this.webcamVideoElement.width,t=1*this.webcamConfig.resizeHeight/this.webcamVideoElement.height,n=(1-e)/2,r=(1-t)/2,s=n+e,a=t+r;this.cropBox=kd([r,n,a,s],[1,4])}else this.cropBox=kd([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(!Ye().get("IS_BROWSER"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}const n=new ZC(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&ie("user"===this.webcamConfig.facingMode||"environment"===this.webcamConfig.facingMode,(()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`));try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){JC.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise((e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}}))}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=ul(this.webcamVideoElement)}catch(e){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(e)}`)}if(!this.resize)return{value:e,done:!1};try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(e){throw new Error(`Error thrown cropping the video: ${e.message}`)}finally{e.dispose()}}needToResize(){return!(!this.webcamConfig.resizeWidth||!this.webcamConfig.resizeHeight||this.webcamVideoElement.width===this.webcamConfig.resizeWidth&&this.webcamVideoElement.height===this.webcamConfig.resizeHeight)}cropAndResizeFrame(e){return wi((()=>{const t=Eh(Lo(e,"float32"),0);let n;n=Zf.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");const r=n.shape;return vc(n,r.slice(1))}))}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach((e=>e.stop()));try{this.webcamVideoElement.srcObject=null}catch(e){JC.log(e),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}}class QC{}class e$ extends xC{split(e){return new t$(this,e)}}class t$ extends e${constructor(e,t){super(),this.upstream=e,this.impl=new n$(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class n$ extends AC{constructor(e,t){super(),this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){const e=await this.upstream.next();if(e.done)return""!==this.carryover&&(this.outputQueue.push(this.carryover),this.carryover="",!0);const t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(const e of t.slice(0,-1))this.outputQueue.push(e);return this.carryover=t[t.length-1],!0}}var r$=n(62045).hp;class s$ extends xC{decodeUTF8(){return new a$(this)}}class a$ extends e${constructor(e){super(),this.upstream=e,this.impl=new i$(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class i$ extends AC{constructor(e){if(super(),this.upstream=e,Ye().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{const{StringDecoder:e}=n(4530);this.decoder=new e("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){const e=await this.upstream.next();let t,n;return!e.done&&(t=e.value,n=Ye().get("IS_BROWSER")?this.decoder.decode(t,{stream:!0}):this.decoder.write(r$.from(t.buffer)),this.outputQueue.push(n),!0)}}class o$ extends s${constructor(e,t={}){super(),this.file=e,this.options=t,ie(e instanceof Uint8Array||!!Ye().get("IS_BROWSER")&&(e instanceof File||e instanceof Blob),(()=>"FileChunkIterator only supports File, Blob and Uint8Array right now.")),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1048576}summary(){return`FileChunks ${this.file}`}async next(){if(this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size))return{value:null,done:!0};const e=new Promise(((e,t)=>{const n=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)e(new Uint8Array(this.file.slice(this.offset,n)));else{const r=new FileReader;r.onload=n=>{let s=r.result;if(s instanceof ArrayBuffer&&(s=new Uint8Array(s)),!(s instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(s)},r.onabort=e=>t(new Error("Aborted")),r.onerror=e=>t(new Error(e.type));const s=this.file.slice(this.offset,n);r.readAsArrayBuffer(s)}this.offset=n}));return{value:await e,done:!1}}}function u$(e){return"string"==typeof e&&"file://"===e.slice(0,7)}class l$ extends QC{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(u$(this.input)&&Ye().get("IS_NODE")){const e=n(8108);this.input=e.readFileSync(this.input.slice(7))}return new o$(this.input,this.options)}}class c$ extends QC{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return u$(this.url)?new l$(this.url,this.fileOptions).iterator():async function(e,t={},n){let r,s;var a;"string"==typeof e?r=e:(r=e.url,s={method:(a=e).method,headers:a.headers,body:a.body,mode:a.mode,credentials:a.credentials,cache:a.cache,redirect:a.redirect,referrer:a.referrer,integrity:a.integrity});const i=await(n||Qs)(r,s);if(i.ok){const e=new Uint8Array(await i.arrayBuffer());return new o$(e,t)}throw new Error(i.statusText)}(this.url,this.fileOptions)}}function h$(e,t={}){return new XC(new c$(e),t)}function p$(e){const t=bC(e);return zC((async()=>t))}function d$(e){return zC((async()=>{const t=await e();return bC((()=>t.next()))}))}async function f$(e,t){return ZC.create(e,t)}async function m$(e){return YC.create(e)}const g$="4.20.0";function y$(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&ie("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the CPU backend.`))}))}const b$=_d;class x$ extends Y{nextDataId(){return x$.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new X(this,yi())}write(e,t,n){this.firstUse&&(this.firstUse=!1,Ye().get("IS_NODE")&&ks("\n============================\nHi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. \n============================"));const r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&Ee(n[0])){const s=n.map((e=>ea(e)));r=this.write(s,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){this.data.get(e).refCount++}decRef(e){this.data.has(e)&&this.data.get(e).refCount--}move(e,t,n,r,s){this.data.set(e,{values:t,dtype:r,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);return"complex64"===t?Em(this.readSync(n.real.dataId),this.readSync(n.imag.dataId)):ze(this.data.get(e).values,t)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>ta(e)));return Mo(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Mo(e.shape,e.dtype,t)}makeOutput(e,t,n){return yi().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:n}=this.data.get(e);null!=n&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=Zs();return e(),{kernelMs:Zs()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){y$([e],"where");const t=this.readSync(e.dataId);return b$(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}function w$(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}x$.nextDataId=0;const v$={kernelName:nt,backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend;y$(t,"abs");let r=new Float32Array(le(t.shape));return r=w$(n.data.get(t.dataId).values),n.makeOutput(r,t.shape,t.dtype)}};function k$(e){return(t,n,r,s,a)=>{const i=bu(t,n),o=i.length,u=De(i),l=ke(a,le(i)),c=t.length,h=n.length,p=De(t),d=De(n),f=gu(t,i),m=gu(n,i);if(f.length+m.length===0)for(let t=0;t<l.length;++t)l[t]=e(r[t%r.length],s[t%s.length]);else for(let t=0;t<l.length;++t){const n=Ge(t,o,u),a=n.slice(-c);f.forEach((e=>a[e]=0));const i=Ve(a,c,p),g=n.slice(-h);m.forEach((e=>g[e]=0));const y=Ve(g,h,d);l[t]=e(r[i],s[y])}return[l,i]}}function I$(e){const{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,o=n.makeTensorInfo(r.shape,"complex64");return n.data.get(o.dataId).complexTensorInfos={real:n.makeTensorInfo(r.shape,"float32",a),imag:n.makeTensorInfo(s.shape,"float32",i)},o}const N$={kernelName:Et,backendName:"cpu",kernelFunc:I$};function S$(e,t,n="float32"){if("complex64"===n)return I$({inputs:{real:S$(e,t,"float32"),imag:S$(e,t,"float32")},backend:e});const r=Be(le(t),n);return e.makeTensorInfo(t,n,r)}function T$(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const C$={kernelName:xn,backendName:"cpu",kernelFunc:T$};function $$(e){const{inputs:t,backend:n}=e,{input:r}=t,s=n.data.get(r.dataId).complexTensorInfos.real,a=n.data.get(s.dataId).values;return n.makeTensorInfo(s.shape,s.dtype,a)}const E$={kernelName:yr,backendName:"cpu",kernelFunc:$$};function A$(e,t,n,r){if("int32"===r)return[t,"int32",Int32Array.from(e)];if("bool"===r){const r=Js([0],n),[s,a]=k$(((e,t)=>e!==t?1:0))(t,[],e,r,"bool");return[a,"bool",s]}throw new Error(`Error in Cast: failed to cast ${n} to ${r}`)}function R$(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dtype:a}=r;if("complex64"===a){if("complex64"===s.dtype)return T$({inputs:{x:s},backend:n});const e=S$(n,s.shape,s.dtype),t=R$({inputs:{x:s},backend:n,attrs:{dtype:"float32"}}),r=I$({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),r}if("complex64"===s.dtype){const e=$$({inputs:{input:s},backend:n}),t=R$({inputs:{x:e},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(e),t}if(!Te(s.dtype,a)){const e=T$({inputs:{x:s},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:a}}const i=n.data.get(s.dataId).values,[o,u,l]=A$(i,s.shape,s.dtype,a);return n.makeTensorInfo(o,u,l)}const O$={kernelName:Tt,backendName:"cpu",kernelFunc:R$};function F$(e,t,n,r){return null==n?({inputs:n,backend:s})=>{const{a,b:i}=n,o=s;y$([a,i],e);const u=o.data.get(a.dataId).values,l=o.data.get(i.dataId).values,c="string"===a.dtype?lg(u):u,h="string"===a.dtype?lg(l):l,p=r||a.dtype,[d,f]=t(a.shape,i.shape,c,h,p);return o.makeTensorInfo(f,p,d)}:({inputs:e,backend:s})=>{const{a,b:i}=e,o=s;if("complex64"===a.dtype||"complex64"===i.dtype){const e=R$({inputs:{x:a},backend:o,attrs:{dtype:"complex64"}}),t=o.data.get(e.dataId),r=t.complexTensorInfos.real,s=t.complexTensorInfos.imag,u=o.data.get(r.dataId).values,l=o.data.get(s.dataId).values,c=R$({inputs:{x:i},backend:o,attrs:{dtype:"complex64"}}),h=o.data.get(c.dataId),p=h.complexTensorInfos.real,d=h.complexTensorInfos.imag,f=o.data.get(p.dataId).values,m=o.data.get(d.dataId).values,[g,y,b]=n(a.shape,i.shape,u,l,f,m),x=o.makeTensorInfo(b,"float32",g),w=o.makeTensorInfo(b,"float32",y),v=I$({inputs:{real:x,imag:w},backend:o});return o.disposeIntermediateTensorInfo(e),o.disposeIntermediateTensorInfo(c),o.disposeIntermediateTensorInfo(x),o.disposeIntermediateTensorInfo(w),v}{const e=o.data.get(a.dataId).values,n=o.data.get(i.dataId).values,s=r||a.dtype,[u,l]=t(a.shape,i.shape,e,n,s);return o.makeTensorInfo(l,s,u)}}}function _$(e){return(t,n,r,s,a,i)=>{const o=bu(t,n),u=le(o),l=o.length,c=De(o),h=ke("float32",u),p=ke("float32",u),d=gu(t,o),f=gu(n,o),m=Em(r,s),g=Em(a,i),y=t.length,b=De(t),x=n.length,w=De(n);if(d.length+f.length===0)for(let t=0;t<h.length;t++){const n=t%m.length,r=t%g.length,s=e(m[2*n],m[2*n+1],g[2*r],g[2*r+1]);h[t]=s.real,p[t]=s.imag}else for(let t=0;t<h.length;t++){const n=Ge(t,l,c),r=n.slice(-y);d.forEach((e=>r[e]=0));const s=Ve(r,y,b),a=n.slice(-x);f.forEach((e=>a[e]=0));const i=Ve(a,x,w),o=e(m[2*s],m[2*s+1],g[2*i],g[2*i+1]);h[t]=o.real,p[t]=o.imag}return[h,p,o]}}const D$=k$(((e,t)=>e+t)),M$=_$(((e,t,n,r)=>({real:e+n,imag:t+r}))),L$=F$(at,D$,M$),z$={kernelName:at,backendName:"cpu",kernelFunc:L$};function P$(e,t,n,r,s){const a=le(r),i=Be(s,n);for(let n=0;n<e.length;n++){const r=e[n];if(r<0)throw new Error("Input x must be non-negative!");r>=s||(i[r]+=a>0?t[n]:1)}return i}function B$(e,t,n,r=!1){const s=e.shape[0],a=e.shape[1],i=Mo([s,n],t.dtype);for(let o=0;o<s;o++)for(let s=0;s<a;s++){const a=e.get(o,s);if(a<0)throw new Error("Input x must be non-negative!");a>=n||(r?i.set(1,o,a):t.size>0?i.set(i.get(o,a)+t.get(o,s),o,a):i.set(i.get(o,a)+1,o,a))}return i}const W$=k$(((e,t)=>e&t)),U$=F$(It,W$),V$={kernelName:It,backendName:"cpu",kernelFunc:U$};function G$(e){return(t,n,r)=>{const s=Ie(n,t.length);for(let n=0;n<t.length;++n)s[n]=e(t[n],r);return s}}function j$(e,t,n){return H$(e,G$(t),n)}function H$(e,t,n){return({inputs:r,attrs:s,backend:a})=>{const{x:i}=r;y$(i,e);const o=a,u=o.data.get(i.dataId).values;let l;if("string"===i.dtype){if(!Array.isArray(u))throw new Error("String tensor's value was not an instance of Array");l=lg(u)}else l=u;const c=n||i.dtype,h=t(l,c,s);return o.makeTensorInfo(i.shape,c,h)}}const q$=G$((e=>Math.ceil(e))),K$=H$(Ct,q$),X$={kernelName:Ct,backendName:"cpu",kernelFunc:K$};function Y$(e,t,n,r){const s=Ie(n,le(t));if(r&&"string"!==n){let t=0;e.forEach((e=>{const n=le(e.shape);s.set(e.vals,t),t+=n}))}else{let r=0;e.forEach((e=>{const a="string"===n?lg(e.vals):e.vals;let i=0;for(let n=0;n<e.shape[0];++n){const o=n*t[1]+r;for(let t=0;t<e.shape[1];++t)s[o+t]=a[i++]}r+=e.shape[1]}))}return s}const J$=k$(((e,t)=>e===t?1:0)),Z$=F$(sn,J$,null,"bool"),Q$={kernelName:sn,backendName:"cpu",kernelFunc:Z$},eE=G$((e=>Math.exp(e))),tE=H$(an,eE,"float32"),nE={kernelName:an,backendName:"cpu",kernelFunc:tE},rE=G$((e=>Math.expm1(e))),sE=H$(un,rE),aE={kernelName:un,backendName:"cpu",kernelFunc:sE},iE=G$((e=>Math.floor(e))),oE=H$(pn,iE),uE={kernelName:pn,backendName:"cpu",kernelFunc:oE},lE=k$(((e,t)=>Math.floor(e/t))),cE=F$(dn,lE,null,"int32"),hE={kernelName:dn,backendName:"cpu",kernelFunc:cE};function pE(e,t,n,r,s,a,i,o,u){const l=Mo([r,a],n);for(let n=0;n<r;n++){const r=[];let c=0;for(let t=0;t<s;t++){const a=e[n*s+t];c+=a*i[t],r.push(a)}if(c<0||c>=u/a)throw new Error(`Invalid indices: ${r} does not index into ${o}`);for(let e=0;e<a;e++)l.values[n*a+e]=t.get(...t.indexToLoc(c*a+e))}return l}function dE(e,t,n){const r=Mo(n,e.dtype);for(let n=0;n<r.size;++n){const s=r.indexToLoc(n).slice(),a=s[0],i=s[2],o=t.locToIndex([a,i]);s[2]=t.values[o];const u=e.locToIndex(s);0<=u&&u<e.values.length&&(r.values[n]=e.values[u])}return r}const fE=k$(((e,t)=>e>t?1:0)),mE=F$(yn,fE,null,"bool"),gE={kernelName:yn,backendName:"cpu",kernelFunc:mE},yE=k$(((e,t)=>e>=t?1:0)),bE=F$(bn,yE,null,"bool"),xE={kernelName:bn,backendName:"cpu",kernelFunc:bE},wE=k$(((e,t)=>e<t?1:0)),vE=F$(Tn,wE,null,"bool"),kE={kernelName:Tn,backendName:"cpu",kernelFunc:vE},IE=k$(((e,t)=>e<=t?1:0)),NE=F$(Cn,IE,null,"bool"),SE={kernelName:Cn,backendName:"cpu",kernelFunc:NE};function TE(e,t,n){const r=(t-e)/(n-1),s=Be(n,"float32");s[0]=e;for(let e=1;e<s.length;e++)s[e]=s[e-1]+r;return s}const CE=G$((e=>Math.log(e))),$E=H$(En,CE),EE={kernelName:En,backendName:"cpu",kernelFunc:$E};function AE(e,t,n,r){const s=ke(r,le(n));for(let n=0;n<s.length;++n){const r=n*t;let a=e[r];for(let n=0;n<t;++n){const t=e[r+n];(Number.isNaN(t)||t>a)&&(a=t)}s[n]=a}return s}const RE=k$(((e,t)=>Math.max(e,t))),OE=F$(Wn,RE),FE={kernelName:Wn,backendName:"cpu",kernelFunc:OE},_E=k$(((e,t)=>Math.min(e,t))),DE=F$(Xn,_E),ME={kernelName:Xn,backendName:"cpu",kernelFunc:DE},LE=k$(((e,t)=>e*t)),zE=_$(((e,t,n,r)=>({real:e*n-t*r,imag:e*r+t*n}))),PE=F$(Qn,LE,zE),BE={kernelName:Qn,backendName:"cpu",kernelFunc:PE};function WE(e,t,n){const r=Ys(-1,n);return LE([],t,r,e,n)}const UE={kernelName:er,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;y$(r,"neg");const s=n.data.get(r.dataId).values,[a,i]=WE(s,r.shape,r.dtype);return n.makeTensorInfo(i,r.dtype,a)}},VE=k$(((e,t)=>e!==t?1:0)),GE=F$(tr,VE,null,"bool"),jE={kernelName:tr,backendName:"cpu",kernelFunc:GE};function HE(e,t,n,r,s){const a=t.length,i=le(t),o=De(t),u=De(s),l=ke(n,le(s));for(let t=0;t<i;++t){const n=Ge(t,a,o),s=new Array(n.length);for(let e=0;e<s.length;e++)s[e]=n[r[e]];l[Ve(s,a,u)]=e[t]}return l}function qE(e){const{inputs:t,attrs:n,backend:r}=e,{x:s}=t,{perm:a}=n;y$(s,"transpose");const i=s.shape.length,o=new Array(i);for(let e=0;e<o.length;e++)o[e]=s.shape[a[e]];const u=HE(r.data.get(s.dataId).values,s.shape,s.dtype,a,o);return{dataId:r.write(u,o,s.dtype),shape:o,dtype:s.dtype}}const KE={kernelName:ls,backendName:"cpu",kernelFunc:qE};function XE(e,t,n,r){const[s,a]=gh(e,r),i=Ea(t,"int32"),o=Be(le(s),i),u=le(a);for(let e=0;e<o.length;++e){const t=e*u;let r=1;for(let e=0;e<u;++e)r*=n[t+e];o[e]=r}return{outVals:o,outShape:s,outDtype:i}}const YE={kernelName:pr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r;y$(s,"prod");const o=s.shape.length,u=we(a,s.shape),l=xh(u,o);let c=u,h=s;const p=[];null!=l&&(h=qE({inputs:{x:s},backend:n,attrs:{perm:l}}),p.push(h),c=vh(c.length,o));const d=n.data.get(h.dataId).values,{outVals:f,outShape:m,outDtype:g}=XE(h.shape,h.dtype,d,c);let y=m;return i&&(y=yh(m,u)),p.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(y,g,f)}};function JE(e,t){const n=e.slice(0,t);for(;n.length<t;)n.push(1);for(let r=t;r<e.length;r++)n[t-1]*=e[r];return n}function ZE(e,t,n,r,s,a,i,o){if(0===e.length)throw new Error("paramsNestedSplits must be non empty");if(0===t[0].length)throw new Error("Split tensors must not be scalars");if(function(e,t,n){e.forEach(((e,r)=>{if(e<0||e>=n){const s=Ge(r,t.length,De(t)).join(",");throw new Error(`indices[${s}] = ${e} is not in [0, ${n})`)}}))}(a,i,t[0][0]-1),0===r.length)throw new Error("params.rank must be nonzero");const u=r[0],{outSplits:l,valueSlices:c,numValues:h}=function(e,t,n,r){const s=[];let a=0;const i=t.length-1+n.length,o=new Array(i).fill(null).map((()=>[0]));!function(e,t){for(let n=0;n<e.length;++n){const r=e[n],s=n===e.length-1?t:e[n+1].length;if(0===r.length)throw new Error("Ragged splits may not be empty");if(r[0]<0)throw new Error("Ragged splits must be non-negative");if(r[r.length-1]>s)throw new Error("Ragged splits must not point past values");for(let e=1;e<r.length;++e)if(r[e-1]>r[e])throw new Error("Ragged splits must be sorted in ascending order")}}(n,r);let u=1;for(let e=0;e<t.length-1;++e){u*=t[e];const n=t[e+1];for(let t=1;t<u+1;++t)o[e].push(t*n)}for(let r=0;r<e.length;++r){let i=e[r],u=e[r]+1;for(let e=0;e<n.length;++e){const r=n[e],s=e+t.length-1;if(s>=0){const e=o[s],t=e[e.length-1]-r[i];for(let e=i;e<u;++e)o[s].push(r[e+1]+t)}i=r[i],u=r[u]}u!==i&&(s.push([i,u]),a+=u-i)}return{outSplits:o,valueSlices:s,numValues:a}}(a,i,e,u),p=function(e){const t=[];for(let n=0;n<e.length;++n){const r=Ie("int32",e[n].length);t.push(r),e[n].forEach(((e,t)=>r[t]=e))}return t}(l),d=function(e,t,n,r,s){const a=t.slice();a[0]=s;const i=Ie(n,le(a)),o=e.length;return function(e,t,n,r,s,a){const i=JE(t,2)[1],o=JE(a,2)[1];let u=0;for(const t of n)for(let n=t[0];n<t[1];++n){for(let t=0;t<r;++t)s[u*o+t]=e[n*i+t];++u}}(e,t,r,0===o?0:o/t[0],i,a),[i,a]}(n,r,s,c,h);return[p,d[0],d[1]]}const QE=2147483647;function eA(e,t,n,r,s,a,i){if(t.length>1)throw new Error("starts must be a scalar or vector");if(s.length>1)throw new Error("limits must be a scalar or vector");if(i.length>1)throw new Error("deltas must be a scalar or vector");const o=0===t.length,u=0===s.length,l=0===i.length,c=[];o||c.push(t[0]),u||c.push(s[0]),l||c.push(i[0]);for(let e=1;e<c.length;++e)if(c[e]!==c[e-1])throw new Error("starts, limits, and deltas must have the same shape");const h=0===c.length?1:c[0],p=Ie("int32",h+1);p[0]=0;for(let t=0;t<h;++t){const n=o?e[0]:e[t],s=u?r[0]:r[t],i=l?a[0]:a[t];if(0===i)throw new Error("Requires delta != 0");let c;if(i>0&&s<n||i<0&&s>n)c=0;else if(c=Math.ceil(Math.abs((s-n)/i)),c>QE)throw new Error(`Requires ((limit - start) / delta) <= ${QE}`);p[t+1]=p[t]+c}const d=Ie(n,p[h]);let f=0;for(let t=0;t<h;++t){const n=p[t+1]-p[t];let r=o?e[0]:e[t];const s=l?a[0]:a[t];for(let e=0;e<n;++e)d[f++]=r,r+=s}return[p,d]}var tA=um;class nA{constructor(e,t,n,r,s,a,i,o,u,l){this.shape=e,this.shapeShape=t,this.values=n,this.valuesShape=r,this.valuesDType=s,this.defaultValue=a,this.defaultValueShape=i,this.rowPartitionValues=o,this.rowPartitionValuesShapes=u,this.rowPartitionTypes=cm(l),this.raggedRank=hm(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===tA.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===tA.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){const t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case tA.VALUE_ROWIDS:return nA.getMaxWidthValueRowID(t);case tA.ROW_SPLITS:return nA.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${tA[this.getRowPartitionTypeByDimension(e-1)]}`)}}static getMaxWidthRowSplit(e){const t=e.length;if(0===t||1===t)return 0;let n=0;for(let r=0;r<t-1;++r){const t=e[r+1]-e[r];t>n&&(n=t)}return n}static getMaxWidthValueRowID(e){const t=e.length;if(0===t)return 0;let n=0,r=e[0],s=0;for(let a=1;a<t;++a){const t=e[a];t!==r&&(r=t,s=Math.max(a-n,s),n=a)}return Math.max(t-n,s)}tensorShapeFromTensor(e,t,n=!0){if(0===t.length){if(-1===e[0])return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return sA(e,n)}calculateOutputSize(e){const t=this.valuesShape;pm(this.defaultValueShape,t);const n=this.tensorShapeFromTensor(this.shape,this.shapeShape),r=lm(this.raggedRank,n,t);r[0]<0&&(r[0]=e);for(let e=1;e<=this.raggedRank;++e)r[e]<0&&(r[e]=this.getMaxWidth(e));return r}calculateFirstParentOutputIndex(e,t,n){const r=Math.min(e,n),s=[];let a=0;for(let e=0;e<r;++e,a+=t)s.push(a);for(let t=r;t<e;++t)s.push(-1);return ie(s.length===e,(()=>"Final length of result must be equal to firstDimension.")),s}calculateOutputIndexRowSplit(e,t,n,r){const s=e.length,a=[];for(let i=0;i<s-1;++i){const s=e[i+1]-e[i];let o=Math.min(r,s),u=t[i];-1===u&&(o=0);for(let e=0;e<o;++e)a.push(u),u+=n;for(let e=0;e<s-o;++e)a.push(-1)}if(s>0&&a.length!==e[s-1])throw new Error("Invalid row split size.");return a}calculateOutputIndexValueRowID(e,t,n,r){const s=e.length,a=[];if(0===s)return[];let i=0,o=e[0];if(o>=t.length)throw new Error(`Got currentValueRowId=${o}, which is not less than ${t.length}`);let u=t[o];a.push(u);for(let l=1;l<s;++l){const s=e[l];if(s===o)u>=0&&(++i,i<r?u+=n:u=-1);else{if(i=0,o=s,s>=t.length)throw new Error(`Got nextValueRowId=${s} which is not less than ${t.length}`);u=t[s]}a.push(u)}if(a.length!==e.length)throw new Error("Invalid row ids.");return a}calculateOutputIndex(e,t,n,r){const s=this.getRowPartitionTensor(e),a=this.getRowPartitionTypeByDimension(e);switch(a){case tA.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(s,t,n,r);case tA.ROW_SPLITS:if(s.length-1>t.length)throw new Error(`Row partition size is greater than output size: ${s.length-1} > ${t.length}`);return this.calculateOutputIndexRowSplit(s,t,n,r);default:throw new Error(`Unsupported partition type: ${tA[a]}`)}}getFirstDimensionSize(){const e=this.rowPartitionValues[0];if(0===this.rowPartitionTypes.length)throw new Error("No row_partition_types given.");const t=this.rowPartitionTypes[0];switch(t){case tA.FIRST_DIM_SIZE:return e[0];case tA.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case tA.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${tA[t]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");const e=this.getFirstDimensionSize(),t=this.calculateOutputSize(e),n=new Array(this.raggedRank+1);n[n.length-1]=1;for(let e=n.length-2;e>=0;--e)n[e]=n[e+1]*t[e+1];const r=sA(t,!1),s=Ie(this.valuesDType,le(r));if(n[0]*t[0]>0){let a=this.calculateFirstParentOutputIndex(e,n[0],t[0]);for(let e=1;e<=this.raggedRank;++e)a=this.calculateOutputIndex(e-1,a,n[e],t[e]);this.setOutput(this.raggedRank,a,s,r)}return[r,s]}setOutput(e,t,n,r){if(0===n.length)return;const s=this.values,a=n;let i=r.slice();i=i.slice(e+1);const o=le(i),u=t.length;let l=this.defaultValue;if(l.length!==o&&1!==l.length){const e=this.defaultValueShape;wi((()=>{const t=vc(l,e),n=Lc(t,i);l=n.dataSync()}))}let c=0,h=0,p=0;for(let e=0;e<=u;++e){let r=e<u?t[e]:-1;if(r!==p){if(h<p){const e=s.subarray(c*o);rA(a.subarray(h*o),e,(p-h)*o)}if(e>=u){const e=n.length;r=Math.floor(e/o)}if(r>p)if(1===this.defaultValue.length)a.subarray(p*o,r*o).fill(this.defaultValue[0]),p=r;else for(;r>p;)rA(a.slice(p*o),l,o),++p;r<0?(c=e+1,h=p):(c=e,h=p,p=h+1)}else++p}}}function rA(e,t,n){for(let r=0;r<n;r++)e[r]=t[r]}function sA(e,t){const n=[];for(let r of e){if(r<0){if(!t)throw new Error(`Dimension ${r} must be >= 0`);if(r<-1)throw new Error(`Dimension ${r} must be >= -1`);r=-1}n.push(r)}return n}function aA(e,t,n,r,s,a,i,o,u,l){return new nA(e,t,n,r,s,a,i,o,u,l).compute()}function iA(e,t,n,r){if(e===t||e<t&&n<0||t<e&&n>1)return Be(0,r);const s=Be(Math.abs(Math.ceil((t-e)/n)),r);t<e&&1===n&&(n=-1),s[0]=e;for(let e=1;e<s.length;e++)s[e]=s[e-1]+n;return s}const oA=G$((e=>1/Math.sqrt(e))),uA=H$($r,oA),lA={kernelName:$r,backendName:"cpu",kernelFunc:uA};function cA(e,t,n,r,s,a,i,o,u,l){const c=[r/s,s],h=e.values,p=t.values;if(0===r)return Mo(n,t.dtype);const d=u instanceof ga?u:Mo(c,t.dtype);"string"==typeof u||"number"==typeof u?d.values.fill(u):"boolean"==typeof u&&d.values.fill(+u);for(let e=0;e<a;e++){const a=[];let u=0;for(let t=0;t<i;t++){const n=h[e*i+t];a.push(n),u+=n*o[t]}if(u<0||u>=r/s)throw new Error(`Invalid indices: ${a} does not index into ${n}`);for(let n=0;n<s;n++)l?d.values[u*s+n]+=p[e*s+n]:d.values[u*s+n]=0===t.rank?p[0]:p[e*s+n]}return d}const hA=G$((e=>1/(1+Math.exp(-e)))),pA=j$(zr,(e=>1/(1+Math.exp(-e)))),dA={kernelName:zr,backendName:"cpu",kernelFunc:pA};function fA(e,t,n,r,s){const a=Cl(r,t,n),i=le(n),o=De(r);if(a){const n=$l(t,o);return"string"===s?e.slice(n,n+i):e.subarray(n,n+i)}const u=Mo(r,s,"string"===s?lg(e):e),l=Mo(n,s);for(let e=0;e<l.size;++e){const n=l.indexToLoc(e),r=n.map(((e,n)=>e+t[n]));l.set(u.get(...r),...n)}return"string"===s?cg(l.values):l.values}function mA(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:i}=r;y$(s,"slice");const[o,u]=El(s,a,i);ml(s,o,u);const l=fA(n.data.get(s.dataId).values,o,u,s.shape,s.dtype);return n.makeTensorInfo(u,s.dtype,l)}const gA={kernelName:_r,backendName:"cpu",kernelFunc:mA};function yA(e,t,n,r,s,a,i){const o=t[0],u=a[0],l=new Array(u),c=new Array(o),h=t[1];if(0===u){if(0!==o)throw new Error(Km(o));return[Ie(n,0),[0,h],Ie(s,0),l,c]}let p=!0,d=0;const f=new Array(u).fill(0);for(let t=0;t<o;++t){const n=e[t*h];if(n<0)throw new Error(Xm(t,n));if(n>=u)throw new Error(Ym(t,n,u));++f[n],p=p&&n>=d,d=n}let m=!0;for(let e=0;e<u;++e){const t=0===f[e];l[e]=t,m=m&&!t,f[e]=Math.max(f[e],1),e>0&&(f[e]+=f[e-1])}if(m&&p){const t=e,n=r;for(let e=0;e<o;++e)c[e]=e;return[t,[o,h],n,l,c]}{const t=f[u-1],a=Ie(n,t*h),p=Ie(s,t),d=new Array(u).fill(0);for(let t=0;t<o;++t){const n=e[t*h],s=d[n],i=(0===n?0:f[n-1])+s;d[n]++;for(let n=0;n<h;++n)a[i*h+n]=e[t*h+n];p[i]=r[t],c[t]=i}for(let e=0;e<u;++e)if(0===d[e]){const t=0===e?0:f[e-1];a[t*h+0]=e;for(let e=1;e<h;++e)a[t*h+e]=0;p[t]=i}return[a,[t,h],p,l,c]}}function bA(e,t,n,r,s){const a=le(r),i=t[0],o=s.length,u=[];let l=1,c=-1;for(let e=0;e<o;++e){const t=s[e];if(-1===t){if(-1!==c)throw new Error(Jm(c,e));c=e,u.push(1)}else{if(t<0)throw new Error(Zm(e,t));l*=t,u.push(t)}}if(-1!==c){if(l<=0)throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");const e=Math.trunc(a/l);if(l*e!==a)throw new Error(eg(r,u));u[c]=e}if(le(u)!==a)throw new Error(tg(r,u));const h=r.length,p=[];if(h>0){p[h-1]=1;for(let e=h-2;e>=0;--e)p[e]=p[e+1]*r[e+1]}const d=[];if(o>0){d[o-1]=1;for(let e=o-2;e>=0;--e)d[e]=d[e+1]*u[e+1]}const f=Ie(n,i*o);for(let t=0;t<i;++t){let n=0;for(let r=0;r<h;++r)n+=e[t*h+r]*p[r];for(let e=0;e<o;++e)f[t*o+e]=Math.trunc(n/d[e]),n%=d[e]}return[f,[i,o],u]}function xA(e,t,n,r,s,a=!1,i=0){const o=r.length,u=[t[0],e.length/t[0]],l=u[1],c=o>0?s[o-1]+1:0;if(c<0)throw new Error("segment ids must be >= 0");const h=t.slice();h[0]=c;const p=Ie(n,h.reduce(((e,t)=>e*t),1));if(0===o)return c>0&&p.fill(i),[p,h];if(c<=0)throw new Error("segment ids must be >= 0");let d=0,f=1,m=0,g=s[d];for(;;){let t=0;if(f<o){if(t=s[f],g===t){++f;continue}if(g>=t)throw new Error("segment ids are not increasing")}if(g<0||g>=c)throw new Error(sg(g,c));g>m&&p.fill(i,m*l,g*l);for(let t=d;t<f;++t){const n=r[t];if(n<0||n>=u[0])throw new Error(ag(t,r[t],u[0]));for(let t=0;t<l;t++)p[g*l+t]+=e[n*l+t]}if(a)for(let e=0;e<l;e++)p[g*l+e]/=f-d;if(d=f,++f,m=g+1,g=t,f>o)break}return m<c&&p.fill(i,m*l,c*l),[p,h]}const wA=G$((e=>Math.sqrt(e))),vA=j$(Br,(e=>Math.sqrt(e))),kA={kernelName:Br,backendName:"cpu",kernelFunc:vA},IA=k$(((e,t)=>{const n=e-t;return n*n})),NA=F$(Yr,IA),SA={kernelName:Yr,backendName:"cpu",kernelFunc:NA},TA=G$(((e,t)=>{const{pattern:n,replaceGlobal:r,rewrite:s}=t;return e.replace(new RegExp(n,r?"g":""),s)})),CA=H$(Zr,TA),$A={kernelName:Zr,backendName:"cpu",kernelFunc:CA};function EA(e,t,n,r){const s=Mo(e,t.dtype);for(let e=0;e<s.size;e++){const a=s.indexToLoc(e),i=new Array(a.length);for(let e=0;e<i.length;e++)i[e]=a[e]*n[e]+r[e];s.set(t.get(...i),...a)}return s}class AA{constructor(e,t,n,r,s,a){this.separator=ea(e),this.nGramWidths=t,this.leftPad=ea(n),this.rightPad=ea(r),this.padWidth=s,this.preserveShort=a}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){const n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,r,s,a){for(let i=0;i<s;++i){const o=this.getPadWidth(a),u=Math.max(0,o-i),l=Math.max(0,o-(s-(i+1))),c=a-(u+l),h=t+(u>0?0:i-o);let p=0;p+=u*this.leftPad.length;for(let t=0;t<c;++t)p+=e[h+t].length;p+=l*this.rightPad.length,p+=(u+l+c-1)*this.separator.length,n[r+i]=new Uint8Array(p);const d=n[r+i];let f=0;const m=e=>e.forEach((e=>d[f++]=e));for(let e=0;e<u;++e)m(this.leftPad),m(this.separator);for(let t=0;t<c-1;++t)m(e[h+t]),m(this.separator);if(c>0){m(e[h+c-1]);for(let e=0;e<l;++e)m(this.separator),m(this.rightPad)}else{for(let e=0;e<l-1;++e)m(this.rightPad),m(this.separator);m(this.rightPad)}}}compute(e,t){const n=e.length,r=t.length;if(r>0){let e=t[0];if(0!==e)throw new Error(`First split value must be 0, got ${e}`);for(let s=1;s<r;++s){let r=t[s]>=e;if(r=r&&t[s]<=n,!r)throw new Error(`Invalid split value ${t[s]}, must be in [${e}, ${n}]`);e=t[s]}if(e!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${e}`)}const s=r-1,a=Ie("int32",r);if(0===n||0===r){const e=new Array(n);for(let e=0;e<=s;++e)a[e]=0;return[e,a]}a[0]=0;for(let e=1;e<=s;++e){const n=t[e]-t[e-1];let r=0;this.nGramWidths.forEach((e=>{r+=this.getNumNGrams(n,e)})),this.preserveShort&&n>0&&0===r&&(r=1),a[e]=a[e-1]+r}const i=new Array(a[s]);for(let n=0;n<s;++n){const r=t[n];let s=a[n];if(this.nGramWidths.forEach((a=>{const o=t[n+1]-t[n],u=this.getNumNGrams(o,a);this.createNGrams(e,r,i,s,u,a),s+=u})),this.preserveShort&&s===a[n]){const a=t[n+1]-t[n];if(0===a)continue;const o=a+2*this.padWidth,u=1;this.createNGrams(e,r,i,s,u,o)}}return[i,a]}}function RA(e,t,n,r,s,a,i,o){return new AA(n,r,s,a,i,o).compute(e,t)}function OA(e,t,n,r){if(!e.length)return;if(0===t.length){for(let t=0;t<e.length;++t)r.push(e.subarray(t,t+1));return}if(1===t.length){const s=t[0];let a=e.indexOf(s);for(;-1!==a;){const t=e.subarray(0,a);n&&0===t.length||r.push(t),a=(e=e.subarray(a+1)).indexOf(s)}return void(n&&0===e.length||r.push(e))}let s=0;for(let a=0;a<e.length+1;a++)if(a===e.length||-1!==t.indexOf(e[a])){const t=e.subarray(s,a);n&&0===t.length||r.push(t),s=a+1}}function FA(e,t,n){const r=e.length,s=[];let a=0,i=0;const o=new Array(r);for(let u=0;u<r;++u){const r=s.length;OA(e[u],t,n,s);const l=s.length-r;o[u]=l,a+=l,i=Math.max(i,l)}const u=Ie("int32",2*a),l=new Array(a),c=[r,i];let h=0;for(let e=0;e<r;++e)for(let t=0;t<o[e];++t)u[2*h]=e,u[2*h+1]=t,l[h]=s[h],++h;return[u,l,c]}function _A(e,t){const n=Ie("int32",e.length);for(let r=0;r<e.length;++r)n[r]=Xs(e[r]).modulo(t).getLowBitsUnsigned();return n}const DA=k$(((e,t)=>e-t)),MA=_$(((e,t,n,r)=>({real:e-n,imag:t-r}))),LA=F$(rs,DA,MA),zA={kernelName:rs,backendName:"cpu",kernelFunc:LA};function PA(e,t){const n=new Array(e.rank);for(let r=0;r<n.length;r++)n[r]=e.shape[r]*t[r];const r=Mo(n,e.dtype);for(let t=0;t<r.values.length;++t){const n=r.indexToLoc(t),s=new Array(e.rank);for(let t=0;t<s.length;t++)s[t]=n[t]%e.shape[t];const a=e.locToIndex(s);r.values[t]=e.values[a]}return r}const BA=(e,t)=>{const n=t.value-e.value;return 0===n?e.index-t.index:n};function WA(e,t,n=0,r=e.length-1){for(;r>n;){if(r-n>600){const s=r-n+1,a=t-n+1,i=Math.log(s),o=.5*Math.exp(2*i/3),u=.5*Math.sqrt(i*o*(s-o)/s)*Math.sign(a-s/2);WA(e,t,Math.max(n,Math.floor(t-a*o/s+u)),Math.min(r,Math.floor(t+(s-a)*o/s+u)))}const s=e[t];let a=n,i=r;for(ne(e,n,t),BA(e[r],s)>0&&ne(e,n,r);a<i;){for(ne(e,a,i),a++,i--;BA(e[a],s)<0;)a+=1;for(;BA(e[i],s)>0;)i-=1}0===BA(e[n],s)?ne(e,n,i):(i+=1,ne(e,i,r)),i<=t&&(n=i+1),t<=i&&(r=i-1)}}function UA(e,t,n,r,s){const a=t[t.length-1],[i,o]=[e.length/a,a],u=ke(n,i*r),l=ke("int32",i*r);for(let t=0;t<i;t++){const n=t*o,a=e.subarray(n,n+o);let i=new Array(a.length);a.forEach(((e,t)=>i[t]={value:e,index:t})),r<i.length&&(WA(i,r),i=i.slice(0,r)),s&&i.sort(BA);const c=t*r,h=u.subarray(c,c+r),p=l.subarray(c,c+r);for(let e=0;e<r;e++)h[e]=i[e].value,p[e]=i[e].index}const c=t.slice();return c[c.length-1]=r,[Mo(c,n,u),Mo(c,"int32",l)]}function VA(e,t,n,r){const s=we(t,n)[0],a=[1,n[0],1];for(let e=0;e<s;e++)a[0]*=n[e];a[1]=n[s];for(let e=s+1;e<n.length;e++)a[2]*=n[e];const i=new Map,o=new Int32Array(n[s]),u=new ga(a,r,e),l=[],c=1===a[0]&&1===a[2];for(let t=0;t<n[s];t++){let n;if(c)n=e[t].toString();else{const e=[];for(let n=0;n<a[0];n++)for(let r=0;r<a[2];r++)e.push(u.get(n,t,r));n=e.join(",")}const r=i.get(n);if(null!=r)o[t]=r;else{const e=i.size;i.set(n,e),o[t]=e,l.push(t)}}const h=a.slice();h[1]=i.size;const p=new ga(h,r);l.forEach(((e,t)=>{for(let n=0;n<a[0];n++)for(let r=0;r<a[2];r++)p.set(u.get(n,e,r),n,t,r)}));const d=n.slice();return d[s]=h[1],{outputValues:p.values,outputShape:d,indices:o}}const GA="4.20.0";Ai("cpu",(()=>new x$),1);const jA=j$(tn,(e=>e>=0?e:Math.exp(e)-1)),HA={kernelName:tn,backendName:"cpu",kernelFunc:jA};function qA(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r;y$([s],"leakyRelu");const i=le(s.shape),o=n.data.get(s.dataId).values,u=ke("float32",i);for(let e=0;e<o.length;e++)u[e]=o[e]<0?a*o[e]:o[e];return n.makeTensorInfo(s.shape,"float32",u)}const KA={kernelName:Sn,backendName:"cpu",kernelFunc:qA},XA=k$(((e,t)=>e<0?t*e:e));function YA(e){const{inputs:t,backend:n}=e,{x:r,alpha:s}=t;y$([r,s],"prelu");const a=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,[o,u]=XA(r.shape,s.shape,a,i,"float32");return n.makeTensorInfo(u,"float32",o)}const JA={kernelName:hr,backendName:"cpu",kernelFunc:YA},ZA=j$(xr,(e=>Math.max(0,e))),QA={kernelName:xr,backendName:"cpu",kernelFunc:ZA},eR=j$(Sr,(e=>Math.min(Math.max(0,e),6))),tR={kernelName:Sr,backendName:"cpu",kernelFunc:eR};function nR(e,t,n,r,s){if("linear"===n)return T$({inputs:{x:t},backend:e});if("relu"===n)return ZA({inputs:{x:t},backend:e});if("elu"===n)return jA({inputs:{x:t},backend:e});if("relu6"===n)return eR({inputs:{x:t},backend:e});if("prelu"===n)return YA({inputs:{x:t,alpha:r},backend:e});if("leakyrelu"===n)return qA({inputs:{x:t},backend:e,attrs:{alpha:s}});if("sigmoid"===n)return pA({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function rR(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{shape:a}=r,i=le(s.shape),o=xe(a,i),u=le(o);ie(i===u,(()=>`The new shape (${o}) has ${u} elements and the old shape (${s.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`)),n.incRef(s.dataId);const l=n.data.get(s.dataId);if(null!=l.complexTensorInfos){const e=l.complexTensorInfos.real,t=l.complexTensorInfos.imag;e.shape=o,t.shape=o}return{dataId:s.dataId,shape:o,dtype:s.dtype}}const sR={kernelName:wr,backendName:"cpu",kernelFunc:rR};function aR(e){const{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:i,transposeB:o}=r;y$([s,a],"matMul");const u=s.shape.length,l=a.shape.length,c=i?s.shape[u-2]:s.shape[u-1],h=o?a.shape[l-1]:a.shape[l-2],p=i?s.shape[u-1]:s.shape[u-2],d=o?a.shape[l-2]:a.shape[l-1],f=s.shape.slice(0,-2),m=a.shape.slice(0,-2),g=le(f),y=le(m),b=bu(s.shape.slice(0,-2),a.shape.slice(0,-2)).concat([p,d]);ie(c===h,(()=>`Error in matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${s.shape} and ${a.shape} and transposeA=${i} and transposeB=${o} must match.`));const x=o?[y,d,h]:[y,h,d],w=rR({inputs:{x:s},backend:n,attrs:{shape:i?[g,c,p]:[g,p,c]}}),v=rR({inputs:{x:a},backend:n,attrs:{shape:x}}),k=i?w.shape[1]:w.shape[2],I=i?w.shape[2]:w.shape[1],N=o?v.shape[1]:v.shape[2],S=Math.max(g,y),T=n.data.get(w.dataId).values,C=n.data.get(v.dataId).values,$=De(w.shape),E=De(v.shape),[A,R,O]=i?[$[0],1,$[1]]:[$[0],$[1],1],[F,_,D]=o?[1,E[1],E[0]]:[E[1],1,E[0]],M=I*N,L=Mo([S,I,N],w.dtype),z=L.values,P=n.blockSize;for(let e=0;e<S;e++){const t=e%g,n=e%y;for(let r=0;r<I;r+=P){const s=Math.min(r+P,I);for(let a=0;a<N;a+=P){const i=Math.min(a+P,N);for(let o=0;o<k;o+=P){const u=Math.min(o+P,k);for(let l=r;l<s;l++)for(let r=a;r<i;r++){let s=0;for(let e=o;e<u;e++)s+=T[t*A+l*R+e*O]*C[e*F+r*_+n*D];z[e*M+(l*N+r)]+=s}}}}}return n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(v),n.makeTensorInfo(b,L.dtype,L.values)}const iR={kernelName:wt,backendName:"cpu",kernelFunc:aR},oR={kernelName:bs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:i,preluActivationWeights:o}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:h}=r;let p,d,f;const m=[];p=aR({inputs:{a:s,b:a},attrs:{transposeA:u,transposeB:l},backend:n}),i&&(d=L$({inputs:{a:p,b:i},backend:n}),m.push(p),p=d),c&&(f=nR(n,p,c,o,h),m.push(p),p=f);for(const e of m)n.disposeIntermediateTensorInfo(e);return p}},uR=j$(rt,(e=>Math.acos(e))),lR={kernelName:rt,backendName:"cpu",kernelFunc:uR},cR=j$(st,(e=>Math.acosh(e))),hR={kernelName:st,backendName:"cpu",kernelFunc:cR},pR={kernelName:it,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,r=t;y$(t,"addN");const s=r.map((e=>n.data.get(e.dataId).values)),a=Mo(r[0].shape,r[0].dtype),i=a.values;for(let e=0;e<r.length;e++){const t=s[e];for(let e=0;e<i.length;e++)i[e]+=t[e]}return n.makeTensorInfo(a.shape,a.dtype,a.values)}},dR={kernelName:ot,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r;y$(s,"all");const o=we(a,s.shape);let u=o;const l=xh(u,s.shape.length);let c=s;null!=l&&(c=qE({inputs:{x:s},backend:n,attrs:{perm:l}}),u=vh(u.length,s.shape.length)),bh("all",u,c.shape.length);const[h,p]=gh(c.shape,u),d=le(p),f=Be(le(h),c.dtype),m=n.data.get(c.dataId).values;for(let e=0;e<f.length;++e){const t=e*d;let n=m[t];for(let e=0;e<d;++e){const r=m[t+e];n=n&&r}f[e]=n}null!=l&&n.disposeIntermediateTensorInfo(c);const g=n.makeTensorInfo(h,c.dtype,f);if(i){const e=rR({inputs:{x:g},backend:n,attrs:{shape:yh(h,o)}});return n.disposeIntermediateTensorInfo(g),e}return g}},fR={kernelName:ut,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r;y$(s,"any");const o=we(a,s.shape);let u=o;const l=xh(u,s.shape.length);let c=s;null!=l&&(c=qE({inputs:{x:s},backend:n,attrs:{perm:l}}),u=vh(u.length,s.shape.length)),bh("any",u,c.shape.length);const[h,p]=gh(c.shape,u),d=le(p),f=Be(le(h),c.dtype),m=n.data.get(c.dataId).values;for(let e=0;e<f.length;++e){const t=e*d;let n=m[t];for(let e=0;e<d;++e){const r=m[t+e];n=n||r}f[e]=n}null!=l&&n.disposeIntermediateTensorInfo(c);const g=n.makeTensorInfo(h,c.dtype,f);if(i){const e=rR({inputs:{x:g},backend:n,attrs:{shape:yh(h,o)}});return n.disposeIntermediateTensorInfo(g),e}return g}},mR={kernelName:lt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;y$(s,"argMax");let i=we(a,s.shape);const o=xh(i,s.shape.length);let u=s;const l=[];null!=o&&(u=qE({inputs:{x:s},backend:n,attrs:{perm:o}}),l.push(u),i=vh(i.length,u.shape.length)),i=[i[0]],bh("argMax",i,u.shape.length);const[c,h]=gh(u.shape,i),p=Be(le(c),"int32"),d=le(h),f=n.data.get(u.dataId).values;for(let e=0;e<p.length;++e){const t=e*d;let n=f[t],r=0;for(let e=0;e<d;++e){const s=f[t+e];s>n&&(n=s,r=e)}p[e]=r}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",p)}},gR={kernelName:ct,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;y$(s,"argMin");let i=we(a,s.shape);const o=xh(i,s.shape.length);let u=s;const l=[];null!=o&&(u=qE({inputs:{x:s},backend:n,attrs:{perm:o}}),l.push(u),i=vh(i.length,u.shape.length)),i=[i[0]],bh("argMin",i,u.shape.length);const[c,h]=gh(u.shape,i),p=Be(le(c),"int32"),d=le(h),f=n.data.get(u.dataId).values;for(let e=0;e<p.length;++e){const t=e*d;let n=f[t],r=0;for(let e=0;e<d;++e){const s=f[t+e];s<n&&(n=s,r=e)}p[e]=r}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",p)}},yR=j$(ht,(e=>Math.asin(e))),bR={kernelName:ht,backendName:"cpu",kernelFunc:yR},xR=j$(pt,(e=>Math.asinh(e))),wR={kernelName:pt,backendName:"cpu",kernelFunc:xR},vR=j$(dt,(e=>Math.atan(e))),kR={kernelName:dt,backendName:"cpu",kernelFunc:vR},IR=k$(((e,t)=>Math.atan2(e,t))),NR=F$(mt,IR),SR={kernelName:mt,backendName:"cpu",kernelFunc:NR},TR=j$(ft,(e=>Math.atanh(e))),CR={kernelName:ft,backendName:"cpu",kernelFunc:TR};function $R(e,t,n,r,s,a){const i=s.strideHeight,o=s.strideWidth,u=s.dilationHeight,l=s.dilationWidth,c=s.effectiveFilterHeight,h=s.effectiveFilterWidth,p=s.padInfo.top,d=s.padInfo.left,f="max"===a?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Mo(s.outShape,n),g=m.values,y=s.outShape[1]*s.outShape[2]*s.outShape[3],b=s.outShape[2]*s.outShape[3],x=s.outShape[3];for(let t=0;t<s.batchSize;++t){const n=t*y,m=t*r[0];for(let t=0;t<s.inChannels;++t)for(let y=0;y<s.outHeight;++y){const w=y*i-p,v=Math.max(0,w),k=Math.min(s.inHeight,c+w),I=n+y*b;for(let n=0;n<s.outWidth;++n){const i=n*o-d,c=Math.max(0,i),p=Math.min(s.inWidth,h+i);let y=f,b=0,w=0;for(let n=v;n<k;n+=u){const s=m+n*r[1];for(let n=c;n<p;n+=l){const i=e[s+n*r[2]+t];"max"===a&&i>y?y=i:"avg"===a&&(b+=i,w++)}if(isNaN(y))break}g[I+n*x+t]="avg"===a?b/w:y}}}return m}function ER(e,t,n,r,s=!1,a=!1){const i=Mo(r.outShape,"int32"),o=r.strideHeight,u=r.strideWidth,l=r.dilationHeight,c=r.dilationWidth,h=r.effectiveFilterHeight,p=r.effectiveFilterWidth,d=r.padInfo.top,f=r.padInfo.left,m=Mo(t,n,e);for(let e=0;e<r.batchSize;++e)for(let t=0;t<r.inChannels;++t)for(let n=0;n<r.outHeight;++n){const g=n*o-d;let y=g;for(;y<0;)y+=l;const b=Math.min(r.inHeight,h+g);for(let o=0;o<r.outWidth;++o){const h=o*u-f;let d=h;for(;d<0;)d+=c;const x=Math.min(r.inWidth,p+h);let w=Number.NEGATIVE_INFINITY,v=-1;for(let n=y;n<b;n+=l){const i=n-g;for(let o=d;o<x;o+=c){const u=o-h,l=m.get(e,n,o,t);l>w&&(w=l,v=s?a?((e*r.inHeight+n)*r.inWidth+o)*r.inChannels+t:(n*r.inWidth+o)*r.inChannels+t:i*p+u)}}i.set(v,e,n,o,t)}}return i}function AR(e,t,n,r,s,a){const i=s.strideDepth,o=s.strideHeight,u=s.strideWidth,l=s.dilationDepth,c=s.dilationHeight,h=s.dilationWidth,p=s.effectiveFilterDepth,d=s.effectiveFilterHeight,f=s.effectiveFilterWidth,m=s.padInfo.front,g=s.padInfo.top,y=s.padInfo.left,b="max"===a?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=Mo(s.outShape,n),w=x.values,v=s.outShape[1]*s.outShape[2]*s.outShape[3]*s.outShape[4],k=s.outShape[2]*s.outShape[3]*s.outShape[4],I=s.outShape[3]*s.outShape[4],N=s.outShape[4];for(let t=0;t<s.batchSize;++t){const n=t*v,x=t*r[0];for(let t=0;t<s.inChannels;++t)for(let v=0;v<s.outDepth;++v){const S=v*i-m;let T=S;for(;T<0;)T+=l;const C=Math.min(s.inDepth,p+S),$=n+v*k;for(let n=0;n<s.outHeight;++n){const i=n*o-g;let p=i;for(;p<0;)p+=c;const m=Math.min(s.inHeight,d+i),v=$+n*I;for(let n=0;n<s.outWidth;++n){const i=n*u-y;let o=i;for(;o<0;)o+=h;const d=Math.min(s.inWidth,f+i),g=v+n*N;let k=b,I=0,S=0;for(let n=T;n<C;n+=l){const s=x+n*r[1];for(let n=p;n<m;n+=c){const i=s+n*r[2];for(let n=o;n<d;n+=h){const s=e[i+n*r[3]+t];if("max"===a&&s>k?k=s:"avg"===a&&(I+=s,S++),isNaN(k))break}if(isNaN(k))break}if(isNaN(k))break}w[g+t]="avg"===a?I/Math.max(S,1):k}}}}return x}const RR={kernelName:gt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t;y$(s,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:u}=r;ie(yc(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const l=oc(s.shape,a,i,1,o,u);let c;if(1===l.filterWidth&&1===l.filterHeight&&pe(l.inShape,l.outShape))c=T$({inputs:{x:s},backend:n});else{const e=n.data.get(s.dataId).values,t=De(s.shape),r=$R(e,s.shape,s.dtype,t,l,"avg");c=n.makeTensorInfo(l.outShape,s.dtype,r.values)}return c}},OR={kernelName:bt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:u,dataFormat:l}=r;y$(s,"avgPool3d");const c=uc(s.shape,a,i,1,o,u,l),h=AR(n.data.get(s.dataId).values,s.shape,s.dtype,De(s.shape),c,"avg");return n.makeTensorInfo(h.shape,"float32",h.values)}},FR={kernelName:xt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,{filterSize:i,strides:o,pad:u,dimRoundingMode:l}=r;y$([s,a],"avgPool3DGrad");const c=uc(a.shape,i,o,1,u,l),h=c.strideDepth,p=c.strideHeight,d=c.strideWidth,f=c.filterDepth,m=c.filterHeight,g=c.filterWidth,y=c.dilationDepth,b=c.dilationHeight,x=c.dilationWidth,w=c.effectiveFilterDepth,v=c.effectiveFilterHeight,k=c.effectiveFilterWidth,I=w-1-c.padInfo.front,N=k-1-c.padInfo.left,S=v-1-c.padInfo.top,T=Mo(a.shape,"float32"),C=1/(f*m*g),$=n.bufferSync(s);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inDepth;++n)for(let r=0;r<c.inHeight;++r)for(let s=0;s<c.inWidth;++s){const a=n-I,i=r-S,o=s-N;let u=0;for(let n=0;n<w;n+=y){const r=(a+n)/h;if(!(r<0||r>=c.outDepth||Math.floor(r)!==r))for(let n=0;n<v;n+=b){const s=(i+n)/p;if(!(s<0||s>=c.outHeight||Math.floor(s)!==s))for(let n=0;n<k;n+=x){const a=(o+n)/d;a<0||a>=c.outWidth||Math.floor(a)!==a||(u+=$.get(e,r,s,a,t))}}}T.set(u*C,e,n,r,s,t)}return n.makeTensorInfo(T.shape,T.dtype,T.values)}},_R={kernelName:yt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,i=a;y$([s,a],"avgPoolGrad");const{filterSize:o,strides:u,pad:l}=r,c=oc(i.shape,o,u,1,l),h=c.strideHeight,p=c.strideWidth,d=c.filterHeight,f=c.filterWidth,m=c.dilationHeight,g=c.dilationWidth,y=c.effectiveFilterHeight,b=c.effectiveFilterWidth,x=b-1-c.padInfo.left,w=y-1-c.padInfo.top,v=Mo(i.shape,"float32"),k=1/(d*f),I=n.data.get(s.dataId).values,N=Mo(s.shape,"float32",I);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inHeight;++n)for(let r=0;r<c.inWidth;++r){const s=n-w,a=r-x;let i=0;for(let n=0;n<y;n+=m){const r=(s+n)/h;if(!(r<0||r>=c.outHeight||Math.floor(r)!==r))for(let n=0;n<b;n+=g){const s=(a+n)/p;s<0||s>=c.outWidth||Math.floor(s)!==s||(i+=N.get(e,r,s,t))}}v.set(i*k,e,n,r,t)}return n.makeTensorInfo(v.shape,v.dtype,v.values)}},DR={kernelName:fn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,scale:a,offset:i,mean:o,variance:u}=t;ie(o.shape.length===u.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),ie(null==i||o.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),ie(null==a||o.shape.length===a.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks.")),y$([s,o,u,a,i],"batchNorm");let{varianceEpsilon:l}=r;null==l&&(l=.001);const c=n.data.get(s.dataId).values,h=n.data.get(o.dataId).values,p=n.data.get(u.dataId).values,d=a?n.data.get(a.dataId).values:new Float32Array([1]),f=i?n.data.get(i.dataId).values:new Float32Array([0]),m=new Float32Array(c.length),g=f.length,y=d.length,b=p.length,x=h.length;let w=0,v=0,k=0,I=0;for(let e=0;e<c.length;++e)m[e]=f[w++]+(c[e]-h[v++])*d[k++]/Math.sqrt(p[I++]+l),w>=g&&(w=0),v>=x&&(v=0),k>=y&&(k=0),I>=b&&(I=0);return n.makeTensorInfo(s.shape,s.dtype,m)}},MR={kernelName:vt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:i}=r;y$([s],"batchToSpaceND");const o=a.reduce(((e,t)=>e*t)),u=gm(s.shape,a,o),l=ym(u.length,a.length),c=bm(s.shape,a,o),h=xm(i,a.length),p=wm(c,i,a.length),d=rR({inputs:{x:s},backend:n,attrs:{shape:u}}),f=qE({inputs:{x:d},backend:n,attrs:{perm:l}}),m=rR({inputs:{x:f},backend:n,attrs:{shape:c}}),g=mA({inputs:{x:m},backend:n,attrs:{begin:h,size:p}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}},LR={kernelName:kt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:i}=r,o=P$(n.data.get(s.dataId).values,n.data.get(a.dataId).values,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,o)}},zR={kernelName:St,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:r,s1:s}=t,a=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,o=bu(Array.from(a),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},PR=j$($t,((e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e})),BR={kernelName:$t,backendName:"cpu",kernelFunc:PR},WR={kernelName:At,backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend,r=new Float32Array(le(t.shape)),s=n.data.get(t.dataId),a=s.complexTensorInfos.real,i=s.complexTensorInfos.imag,o=n.data.get(a.dataId).values,u=n.data.get(i.dataId).values;for(let e=0;e<o.length;e++){const t=o[e],n=u[e];r[e]=Math.hypot(t,n)}return n.makeOutput(r,t.shape,"float32")}};function UR(e){const{inputs:t,backend:n}=e,{input:r}=t,s=n.data.get(r.dataId).complexTensorInfos.imag,a=n.data.get(s.dataId).values;return n.makeTensorInfo(s.shape,s.dtype,a)}const VR={kernelName:vn,backendName:"cpu",kernelFunc:UR};function GR(e){const{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=we(s,t[0].shape)[0];im(t.map((e=>e.shape)),a);let i=om(t.map((e=>e.shape)),a);if(0===le(i))return n.makeTensorInfo(i,t[0].dtype,[]);const o=t.filter((e=>le(e.shape)>0));if(1===o.length)return T$({inputs:{x:o[0]},backend:n});if("complex64"===o[0].dtype){const e=o.map((e=>$$({inputs:{input:e},backend:n}))),t=o.map((e=>UR({inputs:{input:e},backend:n}))),r=GR({inputs:e,backend:n,attrs:{axis:a}}),s=GR({inputs:t,backend:n,attrs:{axis:a}}),i=I$({inputs:{real:r,imag:s},backend:n});return e.forEach((e=>n.disposeIntermediateTensorInfo(e))),t.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),i}const u=o.map((e=>{const t=le(e.shape.slice(a));return rR({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),l=u.map((e=>({vals:n.data.get(e.dataId).values,shape:e.shape})));i=om(u.map((e=>e.shape)),1);const c=1===u[0].shape[0],h=Y$(l,i,t[0].dtype,c),p=om(o.map((e=>e.shape)),a),d=n.makeTensorInfo(p,t[0].dtype,h);return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}const jR={kernelName:Rt,backendName:"cpu",kernelFunc:GR};function HR(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dataFormat:u,dilations:l,dimRoundingMode:c}=r;y$([s,a],"conv2d");const h=xc(u),p=lc(s.shape,a.shape,i,l,o,c,!1,h),d=p.filterHeight,f=p.filterWidth,m=p.dilationHeight,g=p.dilationWidth,y=p.padInfo.left,b=p.padInfo.top,x="channelsLast"===p.dataFormat,w=new ga(p.outShape,s.dtype),v=De(s.shape),k=De(a.shape),I=v[0],N=x?v[1]:v[2],S=x?v[2]:1,T=x?1:v[1],C=w.strides[0],$=x?w.strides[1]:w.strides[2],E=x?w.strides[2]:1,A=x?1:w.strides[1],R=n.data.get(s.dataId).values,O=n.data.get(a.dataId).values,F=w.values;for(let e=0;e<p.batchSize;++e){const t=e*I,n=e*C;for(let e=0;e<p.outHeight;++e){const r=n+e*$,s=e*p.strideHeight-b;for(let e=0;e<d;++e){const n=s+e*m;if(n<0||n>=p.inHeight)continue;const a=e*k[0],i=t+n*N;for(let e=0;e<p.outWidth;++e){const t=r+e*E,n=e*p.strideWidth-y;for(let e=0;e<f;++e){const r=n+e*g;if(r<0||r>=p.inWidth)continue;const s=i+r*S;let o=a+e*k[1];for(let e=0;e<p.inChannels;++e){const n=R[s+e*T];for(let e=0;e<p.outChannels;++e)F[t+e*A]+=n*O[o+e];o+=p.outChannels}}}}}}return n.makeTensorInfo(w.shape,w.dtype,F)}const qR={kernelName:Ot,backendName:"cpu",kernelFunc:HR},KR={kernelName:Ft,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,pad:o,dataFormat:u,dimRoundingMode:l,filterShape:c}=r;y$([s,a],"conv2dBackpropFilter");const h=xc(u),p=lc(s.shape,c,i,1,o,l,!1,h),{strideHeight:d,strideWidth:f,filterHeight:m,filterWidth:g}=p,y="channelsLast"===p.dataFormat,b=new ga(p.filterShape,"float32"),x=p.padInfo.left,w=p.padInfo.top,v=n.data.get(s.dataId).values,k=n.data.get(a.dataId).values,I=new ga(s.shape,s.dtype,v),N=new ga(a.shape,a.dtype,k);for(let e=0;e<m;++e){const t=Math.max(0,Math.ceil((w-e)/d)),n=Math.min(p.outHeight,(p.inHeight+w-e)/d);for(let r=0;r<g;++r){const s=Math.max(0,Math.ceil((x-r)/f)),a=Math.min(p.outWidth,(p.inWidth+x-r)/f);for(let i=0;i<p.inChannels;++i)for(let o=0;o<p.outChannels;++o){let u=0;for(let l=0;l<p.batchSize;++l)for(let c=t;c<n;++c){const t=e+c*d-w;for(let e=s;e<a;++e){const n=r+e*f-x;u+=y?I.get(l,t,n,i)*N.get(l,c,e,o):I.get(l,i,t,n)*N.get(l,o,c,e)}}b.set(u,e,r,i,o)}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}},XR={kernelName:_t,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:i,strides:o,pad:u,dataFormat:l,dimRoundingMode:c}=r;y$([s,a],"conv2dBackpropInput");const h=De(a.shape),p=De(s.shape);let d=xc(l);const f=lc(i,a.shape,o,1,u,c,!1,d),m=new ga(f.inShape,"float32"),g=m.values,y=n.data.get(s.dataId).values,b=n.data.get(a.dataId).values,[x,w,v]=h,{batchSize:k,filterHeight:I,filterWidth:N,inChannels:S,inHeight:T,inWidth:C,outChannels:$,outHeight:E,outWidth:A,strideHeight:R,strideWidth:O}=f;d=f.dataFormat;const F=I-1-f.padInfo.top,_=N-1-f.padInfo.left,D="channelsLast"===d,M=m.strides[0],L=D?m.strides[1]:m.strides[2],z=D?m.strides[2]:1,P=D?1:m.strides[1],B=p[0],W=D?p[1]:p[2],U=D?p[2]:1,V=D?1:p[1];for(let e=0;e<k;++e)for(let t=0;t<S;++t)for(let n=0;n<T;++n){const r=n-F,s=Math.max(0,Math.ceil(r/R)),a=Math.min(E,(I+r)/R);for(let i=0;i<C;++i){const o=i-_,u=Math.max(0,Math.ceil(o/O)),l=Math.min(A,(N+o)/O);let c=0;for(let n=s;n<a;++n){const s=n*R-r;for(let r=u;r<l;++r){const a=B*e+W*n+U*r,i=x*(I-1-s)+w*(N-1-(r*O-o))+v*t;for(let e=0;e<$;++e)c+=y[a+V*e]*b[i+e]}}g[M*e+L*n+z*i+P*t]=c}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}},YR={kernelName:Dt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dilations:u}=r;y$([s,a],"conv3d");const l=cc(s.shape,a.shape,i,u,o),{filterDepth:c,filterHeight:h,filterWidth:p,dilationDepth:d,dilationHeight:f,dilationWidth:m,padInfo:g}=l,y=g.front,b=g.left,x=g.top,w=new ga(l.outShape,s.dtype),v=n.data.get(s.dataId).values,k=n.data.get(a.dataId).values,I=w.values,N=De(s.shape),S=De(a.shape);for(let e=0;e<l.batchSize;++e){const t=e*N[0],n=e*w.strides[0];for(let e=0;e<l.outDepth;++e){const r=n+e*w.strides[1],s=e*l.strideDepth-y;for(let e=0;e<c;++e){const n=s+e*d;if(n<0||n>=l.inDepth)continue;const a=e*S[0],i=t+n*N[1];for(let e=0;e<l.outHeight;++e){const t=r+e*w.strides[2],n=e*l.strideHeight-x;for(let e=0;e<h;++e){const r=n+e*f;if(r<0||r>=l.inHeight)continue;const s=a+e*S[1],o=i+r*N[2];for(let e=0;e<l.outWidth;++e){const n=t+e*l.outChannels,r=e*l.strideWidth-b;for(let e=0;e<p;++e){const t=r+e*m;if(t<0||t>=l.inWidth)continue;const a=s+e*S[2],i=o+t*l.inChannels;let u=a;for(let e=0;e<l.inChannels;++e){const t=v[i+e];for(let e=0;e<l.outChannels;++e)I[n+e]+=t*k[u+e];u+=l.outChannels}}}}}}}}return n.makeTensorInfo(w.shape,w.dtype,w.values)}},JR={kernelName:Mt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,pad:o,filterShape:u}=r;y$([s,a],"conv3dBackpropFilterV2");const l=De(s.shape),c=De(a.shape),h=cc(s.shape,u,i,1,o),p=h.strideDepth,d=h.strideHeight,f=h.strideWidth,m=h.filterDepth,g=h.filterHeight,y=h.filterWidth,b=new ga(h.filterShape,"float32"),x=b.values,[w,v,k,I]=b.strides,N=n.data.get(a.dataId).values,[S,T,C,$]=c,E=n.data.get(s.dataId).values,[A,R,O,F]=l,_=h.padInfo.front,D=h.padInfo.left,M=h.padInfo.top;for(let e=0;e<m;++e){const t=Math.max(0,Math.ceil((_-e)/p)),n=Math.min(h.outDepth,(h.inDepth+_-e)/p),r=e*w;for(let s=0;s<g;++s){const a=Math.max(0,Math.ceil((M-s)/d)),i=Math.min(h.outHeight,(h.inHeight+M-s)/d),o=s*v+r;for(let r=0;r<y;++r){const u=Math.max(0,Math.ceil((D-r)/f)),l=Math.min(h.outWidth,(h.inWidth+D-r)/f),c=r*k+o;for(let o=0;o<h.inChannels;++o){const m=o*I+c;for(let c=0;c<h.outChannels;++c){let g=0;for(let m=0;m<h.batchSize;++m){const h=m*A,y=m*S;for(let m=t;m<n;++m){const t=(e+m*p-_)*R+h,n=m*T+y;for(let e=a;e<i;++e){const a=(s+e*d-M)*O+t,i=e*C+n;for(let e=u;e<l;++e){const t=e*$+i;g+=E[(r+e*f-D)*F+a+o]*N[t+c]}}}}x[m+c]=g}}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}},ZR={kernelName:Lt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:i,strides:o,inputShape:u}=r;y$([s],"conv3dBackpropInputV2");const l=De(s.shape),c=De(a.shape),h=cc(u,a.shape,o,1,i),p=new ga(h.inShape,"float32"),d=p.values,[f,m,g,y]=p.strides,b=n.data.get(s.dataId).values,[x,w,v,k]=l,I=n.data.get(a.dataId).values,[N,S,T,C]=c,{batchSize:$,filterDepth:E,filterHeight:A,filterWidth:R,inChannels:O,inDepth:F,inHeight:_,inWidth:D,outChannels:M,outDepth:L,outHeight:z,outWidth:P,strideDepth:B,strideHeight:W,strideWidth:U}=h,V=E-1-h.padInfo.front,G=A-1-h.padInfo.top,j=R-1-h.padInfo.left;for(let e=0;e<$;++e)for(let t=0;t<O;++t)for(let n=0;n<F;++n){const r=n-V,s=Math.max(0,Math.ceil(r/B)),a=Math.min(L,(E+r)/B);for(let i=0;i<_;++i){const o=i-G,u=Math.max(0,Math.ceil(o/W)),l=Math.min(z,(A+o)/W);for(let c=0;c<D;++c){const h=c-j,p=Math.max(0,Math.ceil(h/U)),$=Math.min(P,(R+h)/U);let O=0;for(let n=s;n<a;++n){const s=n*B-r;for(let r=u;r<l;++r){const a=r*W-o;for(let i=p;i<$;++i){const o=x*e+w*n+v*r+k*i,u=N*(E-1-s)+S*(A-1-a)+T*(R-1-(i*U-h))+C*t;for(let e=0;e<M;++e)O+=b[o+e]*I[u+e]}}}d[f*e+m*n+g*i+y*c+t]=O}}}return n.makeTensorInfo(p.shape,p.dtype,p.values)}},QR=j$(zt,(e=>Math.cos(e))),eO={kernelName:zt,backendName:"cpu",kernelFunc:QR},tO=j$(Pt,(e=>Math.cosh(e))),nO={kernelName:Pt,backendName:"cpu",kernelFunc:tO},rO={kernelName:Ut,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:i}=t,{cropSize:o,method:u,extrapolationValue:l}=r,[c,h,p,d]=s.shape,f=a.shape[0],[m,g]=o,y=Mo([f,m,g,d],"float32"),b=n.data.get(a.dataId).values,x=n.data.get(i.dataId).values,w=n.data.get(s.dataId).values,v=De(s.shape),k=De(y.shape);for(let e=0;e<f;e++){const t=4*e,n=b[t],r=b[t+1],s=b[t+2],a=b[t+3],i=x[e];if(i>=c)continue;const o=m>1?(s-n)*(h-1)/(m-1):0,f=g>1?(a-r)*(p-1)/(g-1):0;for(let t=0;t<m;t++){const c=m>1?n*(h-1)+t*o:.5*(n+s)*(h-1);if(c<0||c>h-1)for(let n=0;n<g;n++)for(let r=0;r<d;r++){const s=r+n*k[2]+t*k[1]+e*k[0];y.values[s]=l}else if("bilinear"===u){const n=Math.floor(c),s=Math.ceil(c),o=c-n;for(let u=0;u<g;u++){const c=g>1?r*(p-1)+u*f:.5*(r+a)*(p-1);if(c<0||c>p-1){for(let n=0;n<d;n++){const r=n+u*k[2]+t*k[1]+e*k[0];y.values[r]=l}continue}const h=Math.floor(c),m=Math.ceil(c),b=c-h;for(let r=0;r<d;r++){let a=r+h*v[2]+n*v[1]+i*v[0];const l=w[a];a=r+m*v[2]+n*v[1]+i*v[0];const c=w[a];a=r+h*v[2]+s*v[1]+i*v[0];const p=w[a];a=r+m*v[2]+s*v[1]+i*v[0];const d=l+(c-l)*b,f=p+(w[a]-p)*b;a=r+u*k[2]+t*k[1]+e*k[0],y.values[a]=d+(f-d)*o}}}else for(let n=0;n<g;++n){const s=g>1?r*(p-1)+n*f:.5*(r+a)*(p-1);if(s<0||s>p-1){for(let r=0;r<d;r++){const s=r+n*k[2]+t*k[1]+e*k[0];y.values[s]=l}continue}const o=Math.round(s),u=Math.round(c);for(let r=0;r<d;r++){const s=r+o*v[2]+u*v[1]+i*v[0],a=r+n*k[2]+t*k[1]+e*k[0];y.values[a]=w[s]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}},sO={kernelName:Bt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:i,reverse:o}=r;y$(s,"cumprod");const u=xh([a],s.shape.length);let l=s;null!=u&&(l=qE({inputs:{x:s},backend:n,attrs:{perm:u}}));const c=vh(1,s.shape.length)[0];if(c!==l.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${l.shape.length-1} but got axis=${c}`);const h=Ea(l.dtype,"int32"),p=Pe(le(l.shape),h),d=n.data.get(l.dataId).values,f=l.shape[l.shape.length-1],m=o?(e,t)=>e+f-t-1:(e,t)=>e+t;for(let e=0;e<d.length;e+=f)for(let t=0;t<f;t++){const n=m(e,t);if(0===t)p[n]=i?1:d[n];else{const r=m(e,t-1);p[n]=i?d[r]*p[r]:d[n]*p[r]}}const g=n.makeTensorInfo(l.shape,h,p);if(null!=u){const e=qE({inputs:{x:g},backend:n,attrs:{perm:wh(u)}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(l),e}return g}},aO={kernelName:Wt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:i,reverse:o}=r;y$(s,"cumsum");const u=xh([a],s.shape.length);let l=s;null!=u&&(l=qE({inputs:{x:s},backend:n,attrs:{perm:u}}));const c=vh(1,s.shape.length)[0];if(c!==l.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${l.shape.length-1} but got axis=${c}`);const h=Ea(l.dtype,"int32"),p=Be(le(l.shape),h),d=n.data.get(l.dataId).values,f=l.shape[l.shape.length-1],m=o?(e,t)=>e+f-t-1:(e,t)=>e+t;for(let e=0;e<d.length;e+=f)for(let t=0;t<f;t++){const n=m(e,t);if(0===t)p[n]=i?0:d[n];else{const r=m(e,t-1);p[n]=i?d[r]+p[r]:d[n]+p[r]}}const g=n.makeTensorInfo(l.shape,h,p);if(null!=u){const e=qE({inputs:{x:g},backend:n,attrs:{perm:wh(u)}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(l),e}return g}},iO={kernelName:Vt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:i,binaryOutput:o}=r;if(1===s.shape.length){const e=P$(n.data.get(s.dataId).values,n.data.get(a.dataId).values,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,e)}if(2===s.shape.length){const e=B$(n.bufferSync(s),n.bufferSync(a),i,o);return n.makeTensorInfo(e.shape,a.dtype,e.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${s.shape.length}.`)}},oO={kernelName:Gt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:i}=r;ie("NHWC"===i,(()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`));const o=s.shape[0],u=s.shape[1],l=s.shape[2],c=s.shape[3],h=u*a,p=l*a,d=c/(a*a),f=n.data.get(s.dataId).values,m=new Float32Array(o*h*p*d);let g=0;for(let e=0;e<o;++e)for(let t=0;t<h;++t){const n=Math.floor(t/a),r=t%a;for(let t=0;t<p;++t){const s=Math.floor(t/a),i=(r*a+t%a)*d;for(let t=0;t<d;++t){const r=t+i+c*(s+l*(n+u*e));m[g++]=f[r]}}}return n.makeTensorInfo([o,h,p,d],s.dtype,m)}};function uO(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dilations:u,dimRoundingMode:l}=r;y$([s,a],"depthwiseConv2DNative");const c=De(s.shape),h=De(a.shape);let p=u;null==p&&(p=[1,1]),ie(yc(i,p),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`));const d=lc(s.shape,a.shape,i,p,o,l,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:y,padInfo:b}=d,x=b.left,w=b.top,v=d.outChannels/d.inChannels,k=new ga(d.outShape,s.dtype),I=n.data.get(s.dataId).values,N=n.data.get(a.dataId).values,S=k.values;for(let e=0;e<d.batchSize;++e){const t=e*c[0],n=e*k.strides[0];for(let e=0;e<d.outHeight;++e){const r=n+e*k.strides[1],s=e*d.strideHeight-w;for(let e=0;e<f;++e){const n=s+e*g;if(n<0||n>=d.inHeight)continue;const a=e*h[0],i=t+n*c[1];for(let e=0;e<d.outWidth;++e){const t=r+e*k.strides[2],n=e*d.strideWidth-x;for(let e=0;e<m;++e){const r=n+e*y;if(r<0||r>=d.inWidth)continue;const s=a+e*h[1],o=i+r*d.inChannels;let u=t,l=s;for(let e=0;e<d.inChannels;++e){const t=I[o+e];for(let e=0;e<v;++e)S[u+e]+=t*N[l+e];u+=v,l+=v}}}}}}return n.makeTensorInfo(k.shape,k.dtype,k.values)}const lO={kernelName:jt,backendName:"cpu",kernelFunc:uO},cO={kernelName:Ht,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,dilations:o,pad:u,dimRoundingMode:l,filterShape:c}=r;y$([s,a],"depthwiseConv2dNativeBackpropFilter");const h=lc(s.shape,c,i,o,u,l,!0),{strideHeight:p,strideWidth:d,filterHeight:f,filterWidth:m}=h,g=new ga(h.filterShape,"float32"),y=h.padInfo.left,b=h.padInfo.top,x=h.outChannels/h.inChannels,w=n.data.get(s.dataId).values,v=new ga(s.shape,s.dtype,w),k=n.data.get(a.dataId).values,I=new ga(a.shape,a.dtype,k);for(let e=0;e<f;++e){const t=Math.max(0,Math.ceil((b-e)/p)),n=Math.min(h.outHeight,(h.inHeight+b-e)/p);for(let r=0;r<m;++r){const s=Math.max(0,Math.ceil((y-r)/d)),a=Math.min(h.outWidth,(h.inWidth+y-r)/d);for(let i=0;i<h.outChannels;++i){const o=Math.trunc(i/x),u=i%x;let l=0;for(let u=0;u<h.batchSize;++u)for(let c=t;c<n;++c){const t=e+c*p-b;for(let e=s;e<a;++e){const n=r+e*d-y;l+=v.get(u,t,n,o)*I.get(u,c,e,i)}}g.set(l,e,r,o,u)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}},hO={kernelName:qt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:i,dilations:o,pad:u,dimRoundingMode:l,inputShape:c}=r;y$([s,a],"depthwiseConv2DNativeBackpropInput");const h=De(s.shape),p=De(a.shape),d=lc(c,a.shape,i,o,u,l,!0),f=new ga(d.inShape,"float32"),m=f.values,[g,y,b]=f.strides,x=n.data.get(s.dataId).values,[w,v,k]=h,I=n.data.get(a.dataId).values,[N,S,T]=p,{batchSize:C,filterHeight:$,filterWidth:E,inChannels:A,inHeight:R,inWidth:O,outChannels:F,outHeight:_,outWidth:D,strideHeight:M,strideWidth:L}=d,z=$-1-d.padInfo.top,P=E-1-d.padInfo.left,B=F/A;for(let e=0;e<C;++e)for(let t=0;t<A;++t)for(let n=0;n<R;++n){const r=n-z,s=Math.max(0,Math.ceil(r/M)),a=Math.min(_,($+r)/M);for(let i=0;i<O;++i){const o=i-P,u=Math.max(0,Math.ceil(o/L)),l=Math.min(D,(E+o)/L);let c=0;for(let n=s;n<a;++n){const s=n*M-r;for(let r=u;r<l;++r){const a=w*e+v*n+k*r,i=N*($-1-s)+S*(E-1-(r*L-o))+T*t;for(let e=0;e<B;++e)c+=x[a+(t*B+e)]*I[i+e]}}m[g*e+y*n+b*i+t]=c}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}},pO={kernelName:Kt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,s=le(r.shape),a=n.data.get(r.dataId).values,i=Mo([s,s],r.dtype),o=i.values;for(let e=0;e<a.length;e++)o[e*s+e]=a[e];const u=[...r.shape,...r.shape];return n.makeTensorInfo(u,i.dtype,i.values)}},dO={kernelName:Xt,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:s}=e,{strides:a,pad:i,dilations:o}=n,u=t,l=u.data.get(r.dataId).values,c=r.shape.length,h=u.data.get(s.dataId).values,p=s.shape.length,{batchSize:d,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:b,padInfo:x,strideHeight:w,strideWidth:v,filterHeight:k,filterWidth:I,dilationHeight:N,dilationWidth:S,outShape:T}=ic(r.shape,s.shape,a,i,"NHWC",o),C=le(T),$=T.length,E=Ie(r.dtype,C);for(let e=0;e<d;++e)for(let t=0;t<y;++t){const n=t*w-x.top;for(let a=0;a<b;++a){const i=a*v-x.left;for(let o=0;o<g;++o){let u=Number.MIN_SAFE_INTEGER;for(let t=0;t<k;++t){const a=n+t*N;if(a>=0&&a<f)for(let n=0;n<I;++n){const d=i+n*S;if(d>=0&&d<m){const i=Ve([e,a,d,o],c,De(r.shape)),f=Ve([t,n,o],p,De(s.shape)),m=l[i]+h[f];m>u&&(u=m)}}}E[Ve([e,t,a,o],$,De(T))]=u}}}return{dataId:u.write(Js(E,r.dtype),T,r.dtype),shape:T,dtype:r.dtype}}},fO={kernelName:Jt,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:s,dy:a}=e,{strides:i,pad:o,dilations:u}=n,l=t,c=Le(r.shape,l.data.get(r.dataId).values),h=Le(s.shape,l.data.get(s.dataId).values),{batchSize:p,inHeight:d,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:w,filterHeight:v,filterWidth:k,dilationHeight:I,dilationWidth:N,outShape:S}=ic(r.shape,s.shape,i,o,"NHWC",u);ie(a.rank===S.length,(()=>`Error in ${Jt}, dy must have the same rank as output ${S.length}, but got ${a.rank}`));const T=Le(S,l.data.get(a.dataId).values),C=We(s.shape,s.dtype);for(let e=0;e<p;++e)for(let t=0;t<g;++t){const n=t*x-b.top;for(let r=0;r<y;++r){const s=r*w-b.left;for(let a=0;a<m;++a){let i=Number.MIN_SAFE_INTEGER,o=0,u=0;for(let t=0;t<v;++t){const r=n+t*I;if(r>=0&&r<d)for(let n=0;n<k;++n){const l=s+n*N;if(l>=0&&l<f){const s=c[e][r][l][a]+h[t][n][a];s>i&&(i=s,o=t,u=n)}}}C[o][u][a]+=T[e][t][r][a]}}}return{dataId:l.write(Js(C,r.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}},mO={kernelName:Yt,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:s,dy:a}=e,{strides:i,pad:o,dilations:u}=n,l=t,c=Le(r.shape,l.data.get(r.dataId).values),h=Le(s.shape,l.data.get(s.dataId).values),{batchSize:p,inHeight:d,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:w,filterHeight:v,filterWidth:k,dilationHeight:I,dilationWidth:N,outShape:S}=ic(r.shape,s.shape,i,o,"NHWC",u);ie(a.rank===S.length,(()=>`Error in ${Yt}, dy must have the same rank as output ${S.length}, but got ${a.rank}`));const T=Le(S,l.data.get(a.dataId).values),C=We(r.shape,r.dtype);for(let e=0;e<p;++e)for(let t=0;t<g;++t){const n=t*x-b.top;for(let r=0;r<y;++r){const s=r*w-b.left;for(let a=0;a<m;++a){let i=Number.MIN_SAFE_INTEGER,o=n<0?0:n,u=s<0?0:s;for(let t=0;t<v;++t){const r=n+t*I;if(r>=0&&r<d)for(let n=0;n<k;++n){const l=s+n*N;if(l>=0&&l<f){const s=c[e][r][l][a]+h[t][n][a];s>i&&(i=s,o=r,u=l)}}}C[e][o][u][a]+=T[e][t][r][a]}}}return{dataId:l.write(Js(C,r.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},gO={kernelName:Zt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:s}=t,{canvas:a,options:i}=r,{contextOptions:o,imageOptions:u}=i||{},l=(null==u?void 0:u.alpha)||1,c=(null==o?void 0:o.contextType)||"2d";if("2d"!==c)throw new Error(`Context type ${o.contextType} is not supported by the CPU backend.`);const h=a.getContext(c,(null==o?void 0:o.contextAttributes)||{});if(null==h)throw new Error(`Could not get the context with ${c} type.`);const[p,d]=s.shape.slice(0,2),f=2===s.shape.length?1:s.shape[2],m=n.data.get(s.dataId).values,g="float32"===s.dtype?255:1,y=new Uint8ClampedArray(d*p*4);for(let e=0;e<p*d;++e){const t=[0,0,0,255*l];for(let n=0;n<f;n++){const r=m[e*f+n];if("float32"===s.dtype){if(r<0||r>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${r}.`)}else if("int32"===s.dtype&&(r<0||r>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${r}.`);1===f?(t[0]=r*g,t[1]=r*g,t[2]=r*g):t[n]=r*g}const n=4*e;y[n+0]=Math.round(t[0]),y[n+1]=Math.round(t[1]),y[n+2]=Math.round(t[2]),y[n+3]=Math.round(t[3])}a.width=d,a.height=p;const b=new ImageData(y,d,p);return h.putImageData(b,0,0),s}};function yO(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r;let o;y$(s,"sum"),o="bool"===s.dtype?R$({inputs:{x:s},backend:n,attrs:{dtype:"int32"}}):T$({inputs:{x:s},backend:n});const u=o.shape.length,l=we(a,o.shape),c=xh(l,u);let h=l,p=o;null!=c&&(p=qE({inputs:{x:o},backend:n,attrs:{perm:c}}),h=vh(h.length,u)),bh("sum",h,p.shape.length);const[d,f]=gh(p.shape,h);let m=S$(n,d,Ea(p.dtype,"int32"));const g=le(f),y=n.data.get(m.dataId).values,b=n.data.get(p.dataId).values;for(let e=0;e<y.length;++e){const t=e*g;let n=0;for(let e=0;e<g;++e)n+=b[t+e];y[e]=n}if(i){const e=m;m=rR({inputs:{x:m},backend:n,attrs:{shape:yh(m.shape,l)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(o),null!=c&&n.disposeIntermediateTensorInfo(p),m}const bO={kernelName:Wr,backendName:"cpu",kernelFunc:yO},xO={kernelName:en,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:i,summedDims:o,idDims:u}=Wm(s,a.length);Vm(i.length,u,a);const{path:l,steps:c}=Gm(o,u),h=c.length;let p=null,d=i.length;const f=[];for(let e=0;e<h;++e){for(const t of c[e]){const{permutationIndices:e,expandDims:r}=Um(d,u[t]);let s;jm(e)?s=a[t]:(s=qE({inputs:{x:a[t]},backend:n,attrs:{perm:e}}),f.push(s));const i=s.shape.slice();for(let e=0;e<r.length;++e)i.splice(r[e],0,1);pe(s.shape,i)||(s=rR({inputs:{x:s},backend:n,attrs:{shape:i}}),f.push(s)),null===p?p=s:(p=PE({inputs:{a:s,b:p},backend:n}),f.push(p))}e<h-1&&(l[e]>=0&&(p=yO({inputs:{x:p},backend:n,attrs:{axis:l[e]-(i.length-d),keepDims:!1}}),f.push(p)),d--)}for(const e of f)e!==p&&n.disposeIntermediateTensorInfo(e);return p}},wO={kernelName:nn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{dy:r,y:s}=t;y$([r,s],"eluGrad");const a=new Float32Array(le(s.shape)),i=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values;for(let e=0;e<i.length;++e){const t=i[e];a[e]=t>=0?o[e]:o[e]*(t+1)}return n.makeTensorInfo(s.shape,"float32",a)}},vO=Im,kO=Nm,IO=Sm,NO=Tm,SO=Cm,TO=$m,CO=j$(rn,(e=>{const t=Math.sign(e),n=Math.abs(e),r=1/(1+vO*n);return t*(1-((((TO*r+SO)*r+NO)*r+IO)*r+kO)*r*Math.exp(-n*n))})),$O={kernelName:rn,backendName:"cpu",kernelFunc:CO};function EO(e){const{inputs:t,backend:n,attrs:r}=e,{input:s}=t,{dim:a}=r,i=s.shape.length,o=s.shape.slice();let u=a;return a<0&&(ie(-(i+1)<=a,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),u=i+a+1),o.splice(u,0,1),rR({inputs:{x:s},backend:n,attrs:{shape:o}})}const AO={kernelName:on,backendName:"cpu",kernelFunc:EO},RO=k$(((e,t)=>e/t)),OO=F$(Qt,RO),FO={kernelName:Qt,backendName:"cpu",kernelFunc:OO};function _O(e,t,n){const r=e.shape,s=r[0],a=r[1],i=n.data.get(e.dataId),o=i.complexTensorInfos.real,u=i.complexTensorInfos.imag,l=[s,a],c=le(l),h=ke("float32",c),p=ke("float32",c);for(let e=0;e<s;e++){const r=mA({inputs:{x:o},backend:n,attrs:{begin:[e,0],size:[1,a]}}),s=mA({inputs:{x:u},backend:n,attrs:{begin:[e,0],size:[1,a]}}),i=I$({inputs:{real:r,imag:s},backend:n}),{real:l,imag:c}=DO(i,t,n),d=Em(l,c);for(let t=0;t<a;t++){const n=Fm(d,t);h[e*a+t]=n.real,p[e*a+t]=n.imag}n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i)}const d=n.makeTensorInfo(l,"float32",h),f=n.makeTensorInfo(l,"float32",p),m=I$({inputs:{real:d,imag:f},backend:n});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),m}function DO(e,t,n){const r=le(e.shape),s=n.data.get(e.dataId),a=n.data.get(s.complexTensorInfos.real.dataId).values,i=n.data.get(s.complexTensorInfos.imag.dataId).values;if((o=r)&o-1){const e=function(e,t,n){const r=new Float32Array(2*t);for(let s=0;s<t;s++){let a=0,i=0;for(let r=0;r<t;r++){const o=Mm(s*r,t,n),u=Fm(e,r);a+=u.real*o.real-u.imag*o.imag,i+=u.real*o.imag+u.imag*o.real}n&&(a/=t,i/=t),_m(r,a,i,s)}return r}(Em(a,i),r,t);return Am(e)}{const s=MO(a,i,r,t,n),o=[e.shape[0],e.shape[1]];if(t){const e=n.makeTensorInfo(o,"float32",s.real),t=n.makeTensorInfo(o,"float32",s.imag),a=n.makeTensorInfo([],"float32",Ys(r,"float32")),i=T$({inputs:{x:a},backend:n}),u=FO.kernelFunc({inputs:{a:e,b:a},backend:n}),l=FO.kernelFunc({inputs:{a:t,b:i},backend:n}),c=n.data.get(u.dataId).values,h=n.data.get(l.dataId).values;return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(l),{real:c,imag:h}}return s}var o}function MO(e,t,n,r,s){if(1===n)return{real:e,imag:t};const a=Em(e,t),i=n/2,o=Rm(a),u=o.real,l=o.imag,c=[u.length],h=s.makeTensorInfo(c,"float32",u),p=s.makeTensorInfo(c,"float32",l),d=I$({inputs:{real:h,imag:p},backend:s}),f=Om(a),m=f.real,g=f.imag,y=[m.length],b=s.makeTensorInfo(y,"float32",m),x=s.makeTensorInfo(y,"float32",g),w=I$({inputs:{real:b,imag:x},backend:s}),v=MO(u,l,i,r,s),k=v.real,I=v.imag,N=[k.length],S=s.makeTensorInfo(N,"float32",k),T=s.makeTensorInfo(N,"float32",I),C=I$({inputs:{real:S,imag:T},backend:s}),$=MO(m,g,i,r,s),E=$.real,A=$.imag,R=[E.length],O=s.makeTensorInfo(R,"float32",E),F=s.makeTensorInfo(R,"float32",A),_=I$({inputs:{real:O,imag:F},backend:s}),D=Dm(n,r),M=[D.real.length],L=s.makeTensorInfo(M,"float32",D.real),z=s.makeTensorInfo(M,"float32",D.imag),P=I$({inputs:{real:L,imag:z},backend:s}),B=PE({inputs:{a:P,b:_},backend:s}),W=L$({inputs:{a:C,b:B},backend:s}),U=LA({inputs:{a:C,b:B},backend:s}),V=$$({inputs:{input:W},backend:s}),G=$$({inputs:{input:U},backend:s}),j=UR({inputs:{input:W},backend:s}),H=UR({inputs:{input:U},backend:s}),q=GR({inputs:[V,G],backend:s,attrs:{axis:0}}),K=GR({inputs:[j,H],backend:s,attrs:{axis:0}}),X=s.data.get(q.dataId).values,Y=s.data.get(K.dataId).values;return s.disposeIntermediateTensorInfo(h),s.disposeIntermediateTensorInfo(p),s.disposeIntermediateTensorInfo(d),s.disposeIntermediateTensorInfo(b),s.disposeIntermediateTensorInfo(x),s.disposeIntermediateTensorInfo(w),s.disposeIntermediateTensorInfo(S),s.disposeIntermediateTensorInfo(T),s.disposeIntermediateTensorInfo(C),s.disposeIntermediateTensorInfo(O),s.disposeIntermediateTensorInfo(F),s.disposeIntermediateTensorInfo(_),s.disposeIntermediateTensorInfo(L),s.disposeIntermediateTensorInfo(z),s.disposeIntermediateTensorInfo(P),s.disposeIntermediateTensorInfo(B),s.disposeIntermediateTensorInfo(W),s.disposeIntermediateTensorInfo(U),s.disposeIntermediateTensorInfo(V),s.disposeIntermediateTensorInfo(j),s.disposeIntermediateTensorInfo(G),s.disposeIntermediateTensorInfo(H),s.disposeIntermediateTensorInfo(q),s.disposeIntermediateTensorInfo(K),{real:X,imag:Y}}const LO={kernelName:ln,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t,s=le(r.shape),a=r.shape[r.shape.length-1],i=rR({inputs:{x:r},backend:n,attrs:{shape:[s/a,a]}}),o=_O(i,!1,n),u=rR({inputs:{x:o},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),u}};function zO(e){const{backend:t,attrs:n}=e,{shape:r,value:s,dtype:a}=n,i=a||Oe(s),o=Ie(i,le(r));return function(e,t,n){e.fill(t)}(o,s),t.makeTensorInfo(r,i,o)}const PO={kernelName:cn,backendName:"cpu",kernelFunc:zO},BO={kernelName:hn,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,s=n,a=ke(r.dtype,le(r.shape)),[i,o,u,l]=r.shape,c=s.data.get(r.dataId).values;for(let e=0;e<i;e++){const t=e*u*o*l;for(let e=0;e<o;e++){const n=e*(u*l);for(let e=0;e<u;e++){const r=e*l;for(let s=0;s<l;s++){const i=Math.round(u-e-1),o=t+n+r+s;let h=c[o];i>=0&&i<u&&(h=c[t+n+i*l+s]),a[o]=h}}}}return{dataId:s.write(a,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},WO={kernelName:xs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:i,preluActivationWeights:o}=t,{strides:u,pad:l,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=r;let m=HR({inputs:{x:s,filter:a},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:h,dimRoundingMode:p}});if(i){const e=m;if("NCHW"===c&&1===i.shape.length&&1!==i.shape[0]){const e=rR({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});m=L$({inputs:{a:m,b:e},backend:n}),n.disposeIntermediateTensorInfo(e)}else m=L$({inputs:{a:m,b:i},backend:n});n.disposeIntermediateTensorInfo(e)}if(d){const e=m;if("NCHW"===c&&"prelu"===d&&1===o.shape.length&&1!==o.shape[0]){const e=rR({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});m=nR(n,m,d,e,f),n.disposeIntermediateTensorInfo(e)}else m=nR(n,m,d,o,f);n.disposeIntermediateTensorInfo(e)}return m}},UO={kernelName:ws,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:i,preluActivationWeights:o}=t,{strides:u,pad:l,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=r;let m=uO({inputs:{x:s,filter:a},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:h,dimRoundingMode:p}});if(i){const e=m;m=L$({inputs:{a:m,b:i},backend:n}),n.disposeIntermediateTensorInfo(e)}if(d){const e=m;m=nR(n,m,d,o,f),n.disposeIntermediateTensorInfo(e)}return m}},VO={kernelName:gn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=le(r.shape),i=s.shape,o=i[i.length-1],[u,l,c,h]=ll(r,s);if(0===l)return n.makeTensorInfo(u,r.dtype,[]);const p=pE(n.data.get(s.dataId).values,n.bufferSync(r),r.dtype,l,o,c,h,r.shape,a);return n.makeTensorInfo(u,r.dtype,p.values)}},GO={kernelName:mn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:i,batchDims:o}=r;y$([s,a],"gatherV2");const u=we(i,s.shape)[0],l=n.data.get(a.dataId).values,c=s.shape[u];for(let e=0;e<l.length;++e){const t=l[e];ie(t<=c-1&&t>=0,(()=>`GatherV2: the index value ${t} is not in [0, ${c-1}]`))}let h=o;null==o&&(h=0);const p=le(a.shape),d=ug(s,a,u,h),f=rR({inputs:{x:s},backend:n,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),m=rR({inputs:{x:a},backend:n,attrs:{shape:[d.batchSize,p/d.batchSize]}}),g=[d.batchSize,d.outerSize,p/d.batchSize,d.sliceSize],y=n.bufferSync(m),b=dE(n.bufferSync(f),y,g);return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.makeTensorInfo(d.outputShape,b.dtype,b.values)}},jO={kernelName:wn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t,s=le(r.shape),a=r.shape[r.shape.length-1],i=rR({inputs:{x:r},backend:n,attrs:{shape:[s/a,a]}}),o=_O(i,!0,n),u=rR({inputs:{x:o},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),u}},HO=j$(kn,(e=>Number.isFinite(e)?1:0),"bool"),qO={kernelName:kn,backendName:"cpu",kernelFunc:HO},KO=j$(In,(e=>Math.abs(e)===1/0?1:0),"bool"),XO={kernelName:In,backendName:"cpu",kernelFunc:KO},YO=j$(Nn,(e=>Number.isNaN(e)?1:0),"bool"),JO={kernelName:Nn,backendName:"cpu",kernelFunc:YO},ZO={kernelName:$n,backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,i=TE(r,s,a);return t.makeTensorInfo([i.length],"float32",i)}},QO=j$(An,(e=>Math.log1p(e))),eF={kernelName:An,backendName:"cpu",kernelFunc:QO},tF=k$(((e,t)=>e&&t)),nF=F$(Rn,tF,null,"bool"),rF={kernelName:Rn,backendName:"cpu",kernelFunc:nF},sF=j$(On,(e=>e?0:1),"bool"),aF={kernelName:On,backendName:"cpu",kernelFunc:sF},iF=k$(((e,t)=>e||t)),oF=F$(Fn,iF,null,"bool"),uF={kernelName:Fn,backendName:"cpu",kernelFunc:oF},lF={kernelName:Ln,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:i,alpha:o,beta:u}=r;y$(s,"LRN");const l=s.shape[3],c=l-1,h=n.data.get(s.dataId).values,p=le(s.shape),d=new Float32Array(p);function f(e){const t=e%l;let n=e-t+Math.max(0,t-a);const r=e-t+Math.min(t+a,c);let s=0;for(;n<=r;n++){const e=h[n];s+=e*e}return s}for(let e=0;e<p;e++){const t=f(e),n=h[e]*Math.pow(i+o*t,-u);d[e]=n}return n.makeTensorInfo(s.shape,s.dtype,d)}},cF={kernelName:zn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,y:a,dy:i}=t,{depthRadius:o,bias:u,alpha:l,beta:c}=r;y$(i,"LRNGrad");const h=le(i.shape),p=i.shape[3],d=n.data.get(i.dataId).values,f=n.data.get(s.dataId).values,m=n.data.get(a.dataId).values,g=new Float32Array(h),y=h;for(let e=0;e<y;e++){const t=e%p,n=e-t+Math.max(0,t-o),r=e-t+Math.min(p,t+o+1);let s=0;for(let e=n;e<r;e++)s+=Math.pow(f[e],2);s=l*s+u;for(let t=n;t<r;t++){let n=-2*l*c*f[t]*m[e]/s;e===t&&(n+=Math.pow(s,-c)),n*=d[e],g[t]+=n}}return n.makeTensorInfo(i.shape,s.dtype,g)}};function hF(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:i}=r,o=n;let u=s.shape;const l=u.length,c=we(a,u);let h=c;const p=xh(h,l);let d=o.data.get(s.dataId).values;if(null!=p){const e=new Array(l);for(let t=0;t<e.length;t++)e[t]=u[p[t]];d=HE(d,u,s.dtype,p,e),h=vh(h.length,l),u=e}y$(s,"max"),bh("max",h,l);const[f,m]=gh(u,h),g=AE(d,le(m),f,s.dtype),y=o.write(g,f,s.dtype);let b=f;return i&&(b=yh(f,c)),{dataId:y,shape:b,dtype:s.dtype}}const pF={kernelName:Bn,backendName:"cpu",kernelFunc:hF},dF={kernelName:Un,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t;y$(s,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:u}=r;ie(yc(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const l=oc(s.shape,a,i,1,o,u);let c;if(1===l.filterWidth&&1===l.filterHeight&&pe(l.inShape,l.outShape))c=T$({inputs:{x:s},backend:n});else{const e=n.data.get(s.dataId).values,t=De(s.shape),r=$R(e,s.shape,s.dtype,t,l,"max");c=n.makeTensorInfo(l.outShape,s.dtype,r.values)}return c}},fF={kernelName:Gn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:u,dataFormat:l}=r;y$(s,"maxPool3d");const c=uc(s.shape,a,i,1,o,u,l),h=AR(n.data.get(s.dataId).values,s.shape,s.dtype,De(s.shape),c,"max");return n.makeTensorInfo(h.shape,"float32",h.values)}},mF={kernelName:jn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,{filterSize:i,strides:o,pad:u,dimRoundingMode:l}=r;y$([s,a],"maxPool3DGrad");const c=uc(a.shape,i,o,1,u,l),h=function(e,t){const n=Mo(t.outShape,"int32"),r=t.strideDepth,s=t.strideHeight,a=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,u=t.dilationWidth,l=t.effectiveFilterDepth,c=t.effectiveFilterHeight,h=t.effectiveFilterWidth,p=t.padInfo.front,d=t.padInfo.top,f=t.padInfo.left;for(let m=0;m<t.batchSize;++m)for(let g=0;g<t.inChannels;++g)for(let y=0;y<t.outDepth;++y){const b=y*r-p;let x=b;for(;x<0;)x+=i;const w=Math.min(t.inDepth,l+b);for(let r=0;r<t.outHeight;++r){const l=r*s-d;let p=l;for(;p<0;)p+=o;const v=Math.min(t.inHeight,c+l);for(let s=0;s<t.outWidth;++s){const d=s*a-f;let k=d;for(;k<0;)k+=u;const I=Math.min(t.inWidth,h+d);let N=Number.NEGATIVE_INFINITY,S=-1;for(let t=x;t<w;t+=i){const n=t-b;for(let r=p;r<v;r+=o){const s=r-l;for(let a=k;a<I;a+=u){const i=a-d,o=e.get(m,t,r,a,g);o>=N&&(N=o,S=n*c*h+s*c+i)}}}n.set(S,m,y,r,s,g)}}}return n}(n.bufferSync(a),c),p=c.strideDepth,d=c.strideHeight,f=c.strideWidth,m=c.dilationDepth,g=c.dilationHeight,y=c.dilationWidth,b=c.effectiveFilterDepth,x=c.effectiveFilterHeight,w=c.effectiveFilterWidth,v=b-1-c.padInfo.front,k=w-1-c.padInfo.left,I=x-1-c.padInfo.top,N=Mo(a.shape,"float32"),S=n.bufferSync(s);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inDepth;++n)for(let r=0;r<c.inHeight;++r)for(let s=0;s<c.inWidth;++s){const a=n-v,i=r-I,o=s-k;let u=0;for(let n=0;n<b;n+=m){const r=(a+n)/p;if(!(r<0||r>=c.outDepth||Math.floor(r)!==r))for(let s=0;s<x;s+=g){const a=(i+s)/d;if(!(a<0||a>=c.outHeight||Math.floor(a)!==a))for(let i=0;i<w;i+=y){const l=(o+i)/f;if(l<0||l>=c.outWidth||Math.floor(l)!==l)continue;const p=b*x*w-1-h.get(e,r,a,l,t)===n*x*w+s*w+i?1:0;0!==p&&(u+=S.get(e,r,a,l,t)*p)}}}N.set(u,e,n,r,s,t)}return n.makeTensorInfo(N.shape,N.dtype,N.values)}},gF={kernelName:Vn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:i}=t,o=a;y$([a,i],"maxPoolGrad");const{filterSize:u,strides:l,pad:c,dimRoundingMode:h}=r,p=oc(o.shape,u,l,1,c,h),d=n.data.get(o.dataId).values,f=Mo(p.outShape,o.dtype,ER(d,o.shape,o.dtype,p).values),m=p.strideHeight,g=p.strideWidth,y=p.dilationHeight,b=p.dilationWidth,x=p.effectiveFilterHeight,w=p.effectiveFilterWidth,v=w-1-p.padInfo.left,k=x-1-p.padInfo.top,I=Mo(o.shape,"float32"),N=n.data.get(s.dataId).values,S=Mo(s.shape,"float32",N);for(let e=0;e<p.batchSize;++e)for(let t=0;t<p.inChannels;++t)for(let n=0;n<p.inHeight;++n)for(let r=0;r<p.inWidth;++r){const s=n-k,a=r-v;let i=0;for(let n=0;n<x;n+=y){const r=(s+n)/m;if(!(r<0||r>=p.outHeight||Math.floor(r)!==r))for(let s=0;s<w;s+=b){const o=(a+s)/g;if(o<0||o>=p.outWidth||Math.floor(o)!==o)continue;const u=x*w-1-f.get(e,r,o,t)===n*w+s?1:0;0!==u&&(i+=S.get(e,r,o,t)*u)}}I.set(i,e,n,r,t)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}},yF={kernelName:Hn,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{filterSize:s,strides:a,pad:i,includeBatchInIndex:o}=t,u=n;y$(r,"MaxPoolWithArgmax");const l=u.data.get(r.dataId).values,c=oc(r.shape,s,a,[1,1],i),[h,p]=function(e,t,n,r,s){const a=$R(e,0,n,De(t),s,"max"),i=ER(e,t,n,s,!0,r);return[a.values,i.values]}(l,r.shape,r.dtype,o,c),d=u.write(h,c.outShape,r.dtype),f=u.write(p,c.outShape,r.dtype);return[{dataId:d,shape:c.outShape,dtype:r.dtype},{dataId:f,shape:c.outShape,dtype:"int32"}]}},bF={kernelName:qn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r,o=we(a,s.shape),u=le(gh(s.shape,o)[1]),l=[],c=n.makeTensorInfo([],"float32",new Float32Array([u]));l.push(c);const h=R$({inputs:{x:s},backend:n,attrs:{dtype:"float32"}});l.push(h);const p=OO({inputs:{a:h,b:c},backend:n});l.push(p);const d=yO({inputs:{x:p},backend:n,attrs:{axis:a,keepDims:i}});return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}},xF={kernelName:Kn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r;y$(s,"min");const o=we(a,s.shape);let u=o;const l=xh(u,s.shape.length);let c=s;null!=l&&(c=qE({inputs:{x:s},backend:n,attrs:{perm:l}}),u=vh(u.length,s.shape.length)),bh("min",u,c.shape.length);const[h,p]=gh(c.shape,u),d=le(p),f=Be(le(h),c.dtype),m=n.data.get(c.dataId).values;for(let e=0;e<f.length;++e){const t=e*d;let n=m[t];for(let e=0;e<d;++e){const r=m[t+e];(Number.isNaN(r)||r<n)&&(n=r)}f[e]=n}null!=l&&n.disposeIntermediateTensorInfo(c);const g=n.makeTensorInfo(h,c.dtype,f);if(i){const e=rR({inputs:{x:g},backend:n,attrs:{shape:yh(h,o)}});return n.disposeIntermediateTensorInfo(g),e}return g}},wF={kernelName:Yn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,mode:i}=r;y$(s,"mirrorPad");const o=a.map(((e,t)=>e[0]+s.shape[t]+e[1])),u=a.map((e=>e[0])),l=a.map(((e,t)=>e[0]+s.shape[t])),c="reflect"===i?0:1,h=n.data.get(s.dataId).values,p=s.shape.length,d=De(s.shape),f=le(o),m=o.length,g=De(o),y=ke(s.dtype,f);for(let e=0;e<f;e++){let t=Ge(e,m,g);for(let e=0;e<m;e++)t[e]<u[e]?t[e]=2*u[e]-t[e]-c:t[e]>=l[e]&&(t[e]=2*(l[e]-1)-t[e]+c);t=t.map(((e,t)=>e-u[t]));const n=Ve(t,p,d);y[e]=h[n]}return{dataId:n.write(y,o,s.dtype),shape:o,dtype:s.dtype}}},vF=k$(((e,t)=>{const n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t})),kF=F$(Jn,vF),IF={kernelName:Jn,backendName:"cpu",kernelFunc:kF};function NF(e){const{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,i=s.shape.length;let o=a;if(-1===o&&(o=i-1),o!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${o}`);const u=we([o],s.shape),l=hF({inputs:{x:s},backend:n,attrs:{reductionIndices:u,keepDims:!1}}),c=yh(l.shape,u),h=rR({inputs:{x:l},backend:n,attrs:{shape:c}}),p=LA({inputs:{a:s,b:h},backend:n}),d=tE({inputs:{x:p},backend:n}),f=yO({inputs:{x:d},backend:n,attrs:{axis:u,keepDims:!1}}),m=rR({inputs:{x:f},backend:n,attrs:{shape:c}}),g=OO({inputs:{a:d,b:m},backend:n});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}const SF={kernelName:Gr,backendName:"cpu",kernelFunc:NF},TF={kernelName:Zn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:i,normalized:o}=r;y$(s,"multinomial");const u=o?s:NF({inputs:{logits:s},backend:n,attrs:{dim:-1}}),l=u.shape[0],c=u.shape[1],h=n.data.get(u.dataId).values,p=[l,a],d=Be(le(p),"int32");for(let e=0;e<l;++e){const t=e*c,n=new Float32Array(c-1);n[0]=h[t];for(let e=1;e<n.length;++e)n[e]=n[e-1]+h[t+e];const r=Fp.alea(i.toString()),s=e*a;for(let e=0;e<a;++e){const t=r();d[s+e]=n.length;for(let r=0;r<n.length;r++)if(t<n[r]){d[s+e]=r;break}}}return o||n.disposeIntermediateTensorInfo(u),n.makeTensorInfo(p,"int32",d)}},CF=mf,$F={kernelName:nr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u}=r;y$(s,"NonMaxSuppression");const l=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,{selectedIndices:h}=CF(l,c,i,o,u);return n.makeTensorInfo([h.length],"int32",new Int32Array(h))}},EF=gf,AF={kernelName:rr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u,padToMaxOutputSize:l}=r;y$(s,"NonMaxSuppressionPadded");const c=n.data.get(s.dataId).values,h=n.data.get(a.dataId).values,{selectedIndices:p,validOutputs:d}=EF(c,h,i,o,u,l);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([d]))]}},RF=yf,OF={kernelName:sr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u,softNmsSigma:l}=r;y$(s,"NonMaxSuppressionWithScore");const c=n.data.get(s.dataId).values,h=n.data.get(a.dataId).values,p=i,d=o,f=u,m=l,{selectedIndices:g,selectedScores:y}=RF(c,h,p,d,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}},FF={kernelName:ir,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{dtype:a,depth:i,onValue:o,offValue:u}=r;y$(s,"oneHot");const l=le(s.shape),c=new Float32Array(l*i);c.fill(u);const h=n.data.get(s.dataId).values;for(let e=0;e<l;++e)h[e]>=0&&h[e]<i&&(c[e*i+h[e]]=o);return n.makeTensorInfo([...s.shape,i],a,c)}};function _F(e){const{inputs:t,backend:n}=e,{x:r}=t;if("string"===r.dtype)throw new Error("zerosLike is not supported for string tensors");if("complex64"===r.dtype){const e=$$({inputs:{input:r},backend:n}),t=_F({inputs:{x:e},backend:n}),s=UR({inputs:{input:r},backend:n}),a=_F({inputs:{x:s},backend:n}),i=I$({inputs:{real:t,imag:a},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),i}return zO({backend:n,attrs:{shape:r.shape,value:0,dtype:r.dtype}})}const DF={kernelName:fs,backendName:"cpu",kernelFunc:_F},MF={kernelName:ar,backendName:"cpu",kernelFunc:function e(t){const{inputs:n,backend:r}=t,{x:s}=n;if("string"===s.dtype)throw new Error("onesLike is not supported for string tensors");if("complex64"===s.dtype){const t=$$({inputs:{input:s},backend:r}),n=e({inputs:{x:t},backend:r}),a=UR({inputs:{input:s},backend:r}),i=_F({inputs:{x:a},backend:r}),o=I$({inputs:{real:n,imag:i},backend:r});return r.disposeIntermediateTensorInfo(t),r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(i),o}return zO({backend:r,attrs:{shape:s.shape,value:1,dtype:s.dtype}})}};function LF(e){const{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(1===t.length)return EO({inputs:{input:t[0]},backend:n,attrs:{dim:s}});const a=t[0].shape,i=t[0].dtype;t.forEach((e=>{oe(a,e.shape,"All tensors passed to stack must have matching shapes"),ie(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],u=GR({inputs:t.map((e=>{const t=EO({inputs:{input:e},backend:n,attrs:{dim:s}});return o.push(t),t})),backend:n,attrs:{axis:s}});return o.forEach((e=>n.disposeIntermediateTensorInfo(e))),u}const zF={kernelName:or,backendName:"cpu",kernelFunc:LF},PF={kernelName:ur,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:i}=r;y$(s,"pad");const o=a.map(((e,t)=>e[0]+s.shape[t]+e[1])),u=a.map((e=>e[0])),l=n.data.get(s.dataId).values,c=le(s.shape),h=s.shape.length,p=De(s.shape),d=le(o),f=o.length,m=De(o),g=ke(s.dtype,d);0!==i&&g.fill(i);for(let e=0;e<c;e++)g[Ve(Ge(e,h,p).map(((e,t)=>e+u[t])),f,m)]=l[e];return{dataId:n.write(g,o,s.dtype),shape:o,dtype:s.dtype}}},BF=k$(((e,t)=>Math.pow(e,t))),WF=F$(cr,BF),UF={kernelName:cr,backendName:"cpu",kernelFunc:WF},VF={kernelName:dr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{paramsNestedSplits:s,paramsDenseValues:a,indices:i}=t,{outputRaggedRank:o}=r,u=s.map((e=>n.data.get(e.dataId).values)),l=s.map((e=>e.shape)),c=n.data.get(a.dataId).values,h=n.data.get(i.dataId).values,[p,d,f]=ZE(u,l,c,a.shape,a.dtype,h,i.shape),m=p.map((e=>n.makeTensorInfo([e.length],"int32",e))),g=n.makeTensorInfo(f,a.dtype,d);return m.concat([g])}},GF={kernelName:fr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{starts:r,limits:s,deltas:a}=t,i=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values,u=n.data.get(a.dataId).values,[l,c]=eA(i,r.shape,r.dtype,o,s.shape,u,a.shape);return[n.makeTensorInfo([l.length],"int32",l),n.makeTensorInfo([c.length],r.dtype,c)]}},jF={kernelName:mr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{shape:s,values:a,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:u}=r,l=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,h=n.data.get(i.dataId).values,p=o.map((e=>n.data.get(e.dataId).values)),d=o.map((e=>e.shape)),[f,m]=aA(l,s.shape,c,a.shape,a.dtype,h,i.shape,p,d,u);return n.makeTensorInfo(f,a.dtype,m)}},HF={kernelName:gr,backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:s,dtype:a,step:i}=n,o=iA(r,s,i,a);return t.makeTensorInfo([o.length],a,o)}},qF=j$(br,(e=>1/e)),KF={kernelName:br,backendName:"cpu",kernelFunc:qF},XF={kernelName:Ir,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:i,size:o}=r;y$(s,"resizeBilinear");const u=De(s.shape),[l,c]=o,[h,p,d,f]=s.shape,m=n.data.get(s.dataId).values,g=new Float32Array(le([h,l,c,f])),y=[a&&l>1?p-1:p,a&&c>1?d-1:d],b=[a&&l>1?l-1:l,a&&c>1?c-1:c];let x=0;const w=y[0]/b[0],v=y[1]/b[1];for(let e=0;e<h;e++)for(let t=0;t<l;t++){let n;n=i?w*(t+.5)-.5:w*t;const r=Math.max(0,Math.floor(n)),s=n-r,a=Math.min(p-1,Math.ceil(n)),o=e*u[0]+r*u[1],l=e*u[0]+a*u[1];for(let e=0;e<c;e++){let t;t=i?v*(e+.5)-.5:v*e;const n=Math.max(0,Math.floor(t)),r=t-n,a=Math.min(d-1,Math.ceil(t)),c=o+n*u[2],h=l+n*u[2],p=o+a*u[2],y=l+a*u[2];for(let e=0;e<f;e++){const t=m[c+e],n=m[h+e],a=t+(m[p+e]-t)*r,i=a+(n+(m[y+e]-n)*r-a)*s;g[x++]=i}}}return n.makeTensorInfo([h,l,c,f],"float32",g)}},YF={kernelName:Nr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:i}=r;y$([a,s],"resizeBilinearGrad");const o=De(s.shape),[u,l,c,h]=s.shape,[,p,d]=a.shape,f=new Float32Array(u*l*c*h),m=[i&&p>1?l-1:l,i&&d>1?c-1:c],g=[i&&p>1?p-1:p,i&&d>1?d-1:d],y=m[0]/g[0],b=m[1]/g[1],x=n.data.get(a.dataId).values;let w=0;for(let e=0;e<u;e++){const t=e*o[0];for(let e=0;e<p;e++){const n=e*y,r=Math.floor(n),s=Math.min(Math.ceil(n),l-1),a=t+r*o[1],i=t+s*o[1],u=n-r,p=1-u;for(let e=0;e<d;e++){const t=e*b,n=Math.floor(t),r=Math.min(Math.ceil(t),c-1),s=t-n,l=1-s,d=a+n*o[2],m=a+r*o[2],g=i+n*o[2],y=i+r*o[2],v=p*l,k=p*s,I=u*l,N=u*s;for(let e=0;e<h;e++){const t=x[w++];f[d+e]+=t*v,f[m+e]+=t*k,f[g+e]+=t*I,f[y+e]+=t*N}}}}return n.makeTensorInfo([u,c,l,h],"float32",f)}},JF={kernelName:vr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:i,size:o}=r;y$(s,"resizeNearestNeighbor");const u=De(s.shape),[l,c]=o,[h,p,d,f]=s.shape,m=n.data.get(s.dataId).values,g=new Float32Array(h*l*c*f),y=[a&&l>1?p-1:p,a&&c>1?d-1:d],b=[a&&l>1?l-1:l,a&&c>1?c-1:c],x=y[0]/b[0],w=y[1]/b[1];let v=0;for(let e=0;e<h;e++){const t=e*u[0];for(let e=0;e<l;e++){const n=i?x*(e+.5):x*e;let r=Math.min(p-1,a?Math.round(n):Math.floor(n));i&&(r=Math.max(0,r));const s=t+r*u[1];for(let e=0;e<c;e++){const t=i?w*(e+.5):w*e;let n=Math.min(d-1,a?Math.round(t):Math.floor(t));i&&(n=Math.max(0,n));const r=s+n*u[2];for(let e=0;e<f;e++){const t=m[r+e];g[v++]=t}}}}return n.makeTensorInfo([h,l,c,f],s.dtype,g)}},ZF={kernelName:kr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:i}=r;y$([a,s],"resizeNearestNeighborGrad");const o=De(s.shape),u=De(a.shape),[l,c,h,p]=s.shape,[,d,f]=a.shape,m=new Float32Array(l*c*h*p),g=n.data.get(a.dataId).values,y=[i&&d>1?c-1:c,i&&f>1?h-1:h],b=[i&&d>1?d-1:d,i&&f>1?f-1:f],x=y[0]/b[0],w=y[1]/b[1],v=1/x,k=1/w,I=2*Math.ceil(v)+2,N=2*Math.ceil(k)+2;for(let e=0;e<l;e++){const t=e*o[0];for(let e=0;e<c;e++){const n=t+e*o[1],r=Math.floor(e*v),s=Math.floor(r-I/2);for(let r=0;r<h;r++){const a=n+r*o[2],l=Math.floor(r*k),y=Math.floor(l-N/2);for(let n=0;n<p;n++){let o=0;for(let a=0;a<I;a++){const l=a+s;if(l<0||l>=d)continue;const p=t+l*u[1],m=l*x;if(e===Math.min(c-1,i?Math.round(m):Math.floor(m)))for(let e=0;e<N;e++){const t=e+y;if(t<0||t>=f)continue;const s=p+t*u[2],a=t*w;r===Math.min(h-1,i?Math.round(a):Math.floor(a))&&(o+=g[s+n])}}m[a+n]=o}}}}return n.makeTensorInfo(s.shape,s.dtype,m)}},QF={kernelName:Tr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r;y$(s,"reverse");const i=s.shape.length,o=we(a,s.shape);if(0===i)return T$({inputs:{x:s},backend:n});const u=new ga(s.shape,s.dtype),l=n.bufferSync(s);for(let e=0;e<u.size;e++){const t=u.indexToLoc(e),n=t.slice();o.forEach((e=>n[e]=s.shape[e]-1-n[e])),u.set(l.get(...n),...t)}return n.makeTensorInfo(u.shape,u.dtype,u.values)}},e_={kernelName:ys,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,{radians:s,fillValue:a,center:i}=t,o=n,u=ke(r.dtype,le(r.shape)),[l,c,h,p]=r.shape,[d,f]=mm(i,c,h),m=Math.sin(s),g=Math.cos(s),y=o.data.get(r.dataId).values;for(let e=0;e<l;e++){const t=e*h*c*p;for(let e=0;e<c;e++){const n=e*(h*p);for(let r=0;r<h;r++){const s=r*p;for(let i=0;i<p;i++){const o=[l,e,r,i],b=o[2],x=o[1];let w=(b-d)*g-(x-f)*m,v=(b-d)*m+(x-f)*g;w=Math.round(w+d),v=Math.round(v+f);let k=a;"number"!=typeof a&&(k=3===i?255:a[i]),w>=0&&w<h&&v>=0&&v<c&&(k=y[t+v*(h*p)+w*p+i]),u[t+n+s+i]=k}}}}return{dataId:o.write(u,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},t_=j$(Cr,(e=>{const t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2==0?t:t+1})),n_={kernelName:Cr,backendName:"cpu",kernelFunc:t_},r_={kernelName:Er,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:i}=r,{sliceRank:o,numUpdates:u,sliceSize:l,strides:c,outputSize:h}=pl(0,s,i),p=cA(n.bufferSync(s),n.bufferSync(a),i,h,l,u,o,c,0,!0);return n.makeTensorInfo(i,p.dtype,p.values)}};function s_(e,t){let n=0,r=e.length,s=0;for(;n<r;)s=Math.floor((n+r)/2),e[s]<t?n=s+1:r=s;return r}function a_(e,t){let n=0,r=e.length,s=0;for(;n<r;)s=Math.floor((n+r)/2),e[s]<=t?n=s+1:r=s;return r}const i_={kernelName:Rr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sortedSequence:s,values:a}=t,{side:i}=r,o=function(e,t,n,r,s,a){const i=Ie("int32",n*s);for(let o=0;o<n;++o){const n=e.slice(o*r,(o+1)*r),u=o*s;for(let e=0;e<s;++e)i[u+e]="left"===a?s_(n,t[e+u]):a_(n,t[e+u])}return i}(n.data.get(s.dataId).values,n.data.get(a.dataId).values,s.shape[0],s.shape[1],a.shape[1],i);return n.makeTensorInfo(a.shape,"int32",o)}},o_={kernelName:Or,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t;y$([r,s,a],"select");const i=r.shape.length,o=n.data.get(r.dataId).values,u=n.data.get(s.dataId).values,l=n.data.get(a.dataId).values,c=Ea(s.dtype,a.dtype),h=Be(le(s.shape),c);let p=0;const d=0===i||i>1||1===s.shape.length?1:le(s.shape.slice(1));for(let e=0;e<o.length;e++)for(let t=0;t<d;t++)1===o[e]?h[p++]=u[e]:h[p++]=l[e];return n.makeTensorInfo(s.shape,c,h)}},u_=vm,l_=km,c_=j$(Fr,(e=>e>=0?l_*e:u_*(Math.exp(e)-1))),h_={kernelName:Fr,backendName:"cpu",kernelFunc:c_},p_=j$(Lr,(e=>e<0?-1:e>0?1:0)),d_={kernelName:Lr,backendName:"cpu",kernelFunc:p_},f_=j$(Dr,(e=>Math.sin(e))),m_={kernelName:Dr,backendName:"cpu",kernelFunc:f_},g_=j$(Mr,(e=>Math.sinh(e))),y_={kernelName:Mr,backendName:"cpu",kernelFunc:g_},b_=Math.log(1.1920928955078125e-7)+2,x_=j$(Pr,(e=>{const t=e>-b_,n=e<b_,r=Math.exp(e);let s;return s=n?r:t?e:Math.log(1+r),s})),w_={kernelName:Pr,backendName:"cpu",kernelFunc:x_},v_={kernelName:Ur,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:i}=r;y$([s],"spaceToBatchND");const o=le(a),u=[[0,0]];u.push(...i);for(let e=1+a.length;e<s.shape.length;++e)u.push([0,0]);const l=PF.kernelFunc({inputs:{x:s},backend:n,attrs:{paddings:u,constantValue:0}}),c=gm(l.shape,a,o,!1),h=ym(c.length,a.length,!1),p=bm(l.shape,a,o,!1),d=rR({inputs:{x:l},backend:n,attrs:{shape:c}}),f=qE({inputs:{x:d},backend:n,attrs:{perm:h}}),m=rR({inputs:{x:f},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),m}},k_={kernelName:jr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{indices:r,values:s,denseShape:a,defaultValue:i}=t;if(1!==a.shape.length)throw new Error(`Dense shape must be a vector, saw:\n ${a.shape}`);if(2!==r.shape.length)throw new Error(`Indices must be a matrix, saw:\n ${r.shape}`);if(1!==s.shape.length)throw new Error(`Values must be a vector, saw:\n ${s.shape}`);if(0!==i.shape.length)throw new Error(`Default value must be a scalar, saw:\n ${i.shape}`);const o=n.data.get(r.dataId).values,u=n.data.get(s.dataId).values,l=n.data.get(a.dataId).values,c=n.data.get(i.dataId).values[0],[h,p,d,f,m]=yA(o,r.shape,r.dtype,u,s.dtype,l,c);return[n.makeTensorInfo(p,r.dtype,h),n.makeTensorInfo([p[0]],s.dtype,d),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map((e=>Number(e))))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}},I_={kernelName:Hr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(2!==r.shape.length)throw new Error(`Input indices should be a matrix but received shape\n ${r.shape}`);if(1!==s.shape.length)throw new Error(`Input shape should be a vector but received shape\n ${s.shape}`);if(1!==a.shape.length)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);const i=Array.from(n.data.get(s.dataId).values),o=n.data.get(r.dataId).values,u=Array.from(n.data.get(a.dataId).values),[l,c,h]=bA(o,r.shape,r.dtype,i,u);return[n.makeTensorInfo(c,r.dtype,l),n.makeTensorInfo([h.length],a.dtype,new Int32Array(h))]}},N_={kernelName:qr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.shape.length)throw new Error(`Indices should be a vector but received shape\n ${s.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${a.shape}`);if(s.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");const i=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values,u=n.data.get(a.dataId).values,[l,c]=xA(i,r.shape,r.dtype,o,u,!0);return n.makeTensorInfo(c,r.dtype,l)}},S_={kernelName:Kr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.shape.length)throw new Error(`Indices should be a vector but received shape\n ${s.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${a.shape}`);if(s.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");const i=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values,u=n.data.get(a.dataId).values,[l,c]=xA(i,r.shape,r.dtype,o,u);return n.makeTensorInfo(c,r.dtype,l)}},T_={kernelName:Xr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:i}=t,{outputShape:o}=r,{sliceRank:u,numUpdates:l,sliceSize:c,strides:h,outputSize:p}=pl(0,s,o),d=!1,f=n.bufferSync(s);let m;switch(a.dtype){case"bool":m=cA(f,n.bufferSync(a),o,p,c,l,u,h,Boolean(n.data.get(i.dataId).values[0]),d);break;case"float32":case"int32":m=cA(f,n.bufferSync(a),o,p,c,l,u,h,n.data.get(i.dataId).values[0],d);break;case"string":m=cA(f,n.bufferSync(a),o,p,c,l,u,h,ta(n.data.get(i.dataId).values[0]),d);break;default:throw new Error(`Unsupported type ${a.dtype}`)}return n.makeTensorInfo(o,m.dtype,m.values)}},C_={kernelName:Vr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:i}=r,o=we(i,s.shape)[0],u=qm(s,a,o),l=new Array(s.shape.length).fill(0),c=s.shape.slice();return u.map((e=>{const t=[...c];t[o]=e;const r=mA({inputs:{x:s},backend:n,attrs:{begin:l,size:t}});return l[o]+=e,r}))}},$_={kernelName:Jr,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,r=t;y$(n,"square");const s=r.data.get(n.dataId).values,a=new Float32Array(s.length);for(let e=0;e<s.length;++e){const t=s[e];a[e]=t*t}return{dataId:r.write(a,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},E_=j$(ms,((e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha})),A_={kernelName:ms,backendName:"cpu",kernelFunc:E_},R_={kernelName:Qr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:i,strides:o,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:h,shrinkAxisMask:p}=r;y$(s,"stridedSlice");const{finalShapeSparse:d,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:w}=Al(s.shape,a,i,o,u,l,c,h,p);let v;if(m)v=rR({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||y){ie(s.shape.length>=1,(()=>`Input must have rank at least 1, got: ${s.shape.length}`));const e=yl(b,x,w),t=mA({inputs:{x:s},backend:n,attrs:{begin:b,size:e}});v=rR({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else{const e=EA(d,n.bufferSync(s),w,b);v=n.makeTensorInfo(f,e.dtype,e.values)}return v}},O_={kernelName:es,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:i,rightPad:o,padWidth:u,preserveShortSequences:l}=r,{data:c,dataSplits:h}=t,p=n.data.get(c.dataId).values,d=n.data.get(h.dataId).values,[f,m]=RA(p,d,s,a,i,o,u,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(h.shape,"int32",m)]}},F_={kernelName:ts,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:i}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(1!==a.shape.length)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(0!==i.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const o=n.data.get(a.dataId).values,u=n.data.get(i.dataId).values[0],[l,c,h]=FA(o,u,s),p=c.length;return[n.makeTensorInfo([p,2],"int32",l),n.makeTensorInfo([p],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(h))]}},__={kernelName:ns,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{numBuckets:s}=r,{input:a}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");const i=_A(n.data.get(a.dataId).values,s);return n.makeTensorInfo(a.shape,"int32",i)}},D_=j$(ss,(e=>Math.tan(e))),M_={kernelName:ss,backendName:"cpu",kernelFunc:D_},L_=j$(as,(e=>Math.tanh(e))),z_={kernelName:Ar,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{tensor:r,indices:s,updates:a}=t,{sliceRank:i,numUpdates:o,sliceSize:u,strides:l,outputSize:c}=pl(0,s,r.shape),h=n.bufferSync(s),p=n.bufferSync(a),d=n.bufferSync(r),f=cA(h,p,r.shape,c,u,o,i,l,d,!1);return n.makeTensorInfo(r.shape,f.dtype,f.values)}},P_={kernelName:is,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;y$(s,"tile");const i=PA(n.bufferSync(s),a);return n.makeTensorInfo(i.shape,i.dtype,i.values)}},B_={kernelName:os,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:i}=r;y$(s,"topk");const o=n.data.get(s.dataId).values,[u,l]=UA(o,s.shape,s.dtype,a,i);return[n.makeTensorInfo(u.shape,u.dtype,u.values),n.makeTensorInfo(l.shape,l.dtype,l.values)]}},W_={kernelName:us,backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{image:s,transforms:a}=t,{interpolation:i,fillMode:o,fillValue:u,outputShape:l}=n,[c,h,p,d]=s.shape,[f,m]=null!=l?l:[h,p],g=[c,f,m,d],y=De(s.shape),b=y[0],x=y[1],w=y[2],v=De(g),k=v[0],I=v[1],N=v[2],S=ke(s.dtype,le(g));S.fill(u);const T=r.data.get(s.dataId).values,C=r.data.get(a.dataId).values;for(let e=0;e<c;++e){const t=1===a.shape[0]?C:C.subarray(8*e,8*e+8);for(let n=0;n<f;++n)for(let r=0;r<m;++r)for(let s=0;s<d;++s){let a;const l=t[6]*r+t[7]*n+1;if(0===l)continue;const c=(t[0]*r+t[1]*n+t[2])/l,d=(t[3]*r+t[4]*n+t[5])/l,f=U_(c,p,o),m=U_(d,h,o);switch(i){case"nearest":a=G_(T,h,p,b,x,w,e,m,f,s,u);break;case"bilinear":a=j_(T,h,p,b,x,w,e,m,f,s,u);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}S[e*k+n*I+r*N+s]=a}return r.makeTensorInfo(g,s.dtype,S)}return{dataId:r.write(S,g,s.dtype),shape:s.shape,dtype:s.dtype}}};function U_(e,t,n){switch(n){case"reflect":return function(e,t){let n=e;if(n<0)if(t<=1)n=0;else{const e=2*t;n<e&&(n=e*Math.trunc(-n/e)+n),n=n<-t?n+e:-n-1}else if(n>t-1)if(t<=1)n=0;else{const e=2*t;n-=e*Math.trunc(n/e),n>=t&&(n=e-n-1)}return ee(0,n,t-1)}(e,t);case"wrap":return function(e,t){let n=e;if(n<0)if(t<=1)n=0;else{const e=t-1;n+=t*(Math.trunc(-n/e)+1)}else if(n>t-1)if(t<=1)n=0;else{const e=t-1;n-=t*Math.trunc(n/e)}return ee(0,n,t-1)}(e,t);case"nearest":return function(e,t){return ee(0,e,t-1)}(e,t);default:return function(e,t){return e}(e)}}function V_(e,t,n,r,s,a,i,o,u,l,c){return 0<=o&&o<t&&0<=u&&u<n?e[i*r+o*s+u*a+l]:c}function G_(e,t,n,r,s,a,i,o,u,l,c){return V_(e,t,n,r,s,a,i,Math.round(o),Math.round(u),l,c)}function j_(e,t,n,r,s,a,i,o,u,l,c){const h=Math.floor(o),p=Math.floor(u),d=h+1,f=p+1;return(d-o)*((f-u)*V_(e,t,n,r,s,a,i,h,p,l,c)+(u-p)*V_(e,t,n,r,s,a,i,h,f,l,c))+(o-h)*((f-u)*V_(e,t,n,r,s,a,i,d,p,l,c)+(u-p)*V_(e,t,n,r,s,a,i,d,f,l,c))}const H_={kernelName:cs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;y$(a,"unique");const i=r.data.get(a.dataId).values,{outputValues:o,outputShape:u,indices:l}=VA(i,s,a.shape,a.dtype);return[r.makeTensorInfo(u,a.dtype,o),r.makeTensorInfo([l.length],"int32",l)]}},q_={kernelName:hs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:s}=t;let{axis:a}=r;a<0&&(a+=s.shape.length);const i=s.shape.length,o=s.shape[a],u=new Array(i-1);let l=0;for(let e=0;e<i;e++)e!==a&&(u[l++]=s.shape[e]);const c=new Array(i).fill(0),h=s.shape.slice();h[a]=1;const p=new Array(o);for(let e=0;e<p.length;e++){c[a]=e;const t=mA({inputs:{x:s},backend:n,attrs:{begin:c,size:h}});p[e]=rR({inputs:{x:t},backend:n,attrs:{shape:u}}),n.disposeIntermediateTensorInfo(t)}return p}},K_={kernelName:ps,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:i}=r;y$(s,"unsortedSegmentSum");const o=[],u=[],l=s.shape.length-a.shape.length;let c=a;for(let e=0;e<l;++e){const t=EO({inputs:{input:c},backend:n,attrs:{dim:e+1}});c=t,u.push(t)}for(let e=0;e<i;++e){const t=Ys(e,"int32"),r=n.makeTensorInfo([],"int32",t),a=Z$({inputs:{a:r,b:c},backend:n}),i=R$({inputs:{x:a},backend:n,attrs:{dtype:"float32"}}),l=PE({inputs:{a:i,b:s},backend:n}),h=yO({inputs:{x:l},backend:n,attrs:{axis:0,keepDims:!1}});o.push(h),u.push(r),u.push(a),u.push(i),u.push(l),u.push(h)}const h=LF({inputs:o,backend:n,attrs:{axis:0}});return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),h}},X_=[oR,v$,lR,hR,z$,pR,dR,fR,mR,gR,bR,wR,kR,SR,CR,RR,OR,FR,_R,iR,DR,MR,LR,V$,zR,O$,X$,BR,N$,WR,jR,qR,KR,XR,YR,JR,ZR,eO,nO,rO,sO,aO,iO,oO,lO,cO,hO,pO,dO,fO,mO,gO,xO,HA,wO,Q$,$O,nE,AO,aE,LO,PO,BO,uE,hE,WO,UO,VO,GO,gE,xE,C$,jO,VR,qO,XO,JO,KA,kE,SE,ZO,EE,eF,rF,aF,uF,lF,cF,pF,FE,dF,fF,mF,gF,yF,bF,xF,ME,wF,IF,TF,BE,UE,$F,AF,OF,jE,FF,MF,zF,PF,UF,JA,YE,VF,GF,jF,HF,E$,FO,KF,QA,tR,sR,XF,YF,JF,ZF,QF,e_,n_,lA,r_,i_,o_,h_,dA,d_,m_,y_,gA,SF,w_,v_,k_,I_,N_,S_,T_,C_,kA,$_,SA,$A,A_,R_,O_,F_,__,zA,bO,M_,{kernelName:as,backendName:"cpu",kernelFunc:L_},z_,P_,B_,W_,KE,H_,q_,K_,DF];for(const e of X_)Es(e);var Y_=n(96763);const J_={},Z_={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Q_(e,t){J_[e]=t}function eD(e,t){if(!(e in J_)||null!=t){const n=function(e,t){if(1!==e&&2!==e)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const n=null==t?function(e){if(Ye().getBool("IS_SAFARI")||"undefined"==typeof OffscreenCanvas||2!==e){if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}return new OffscreenCanvas(300,150)}(e):t;return n.addEventListener("webglcontextlost",(t=>{t.preventDefault(),delete J_[e]}),!1),Ye().getBool("SOFTWARE_WEBGL_ENABLED")&&(Z_.failIfMajorPerformanceCaveat=!1),1===e?n.getContext("webgl",Z_)||n.getContext("experimental-webgl",Z_):n.getContext("webgl2",Z_)}(e,t);if(null===n)return Y_.log("Could not get context for WebGL version",e),null;J_[e]=n}const n=J_[e];return null==n||n.isContextLost()?(delete J_[e],eD(e)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),J_[e])}var tD,nD,rD;function sD(e,t){return[t,e]}function aD(e){const t=le(e);return me(Math.ceil(t/4))}function iD(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function oD(e,t){const n=e;let r,s,a,i,o,u,l,c,h,p;return 2===Ye().getNumber("WEBGL_VERSION")?(r=n.R32F,s=n.R16F,a=n.RGBA16F,i=n.RGBA32F,o=n.RED,l=4,c=1,h=n.HALF_FLOAT,p=n.FLOAT,u=n.RGBA8):(r=e.RGBA,s=e.RGBA,a=e.RGBA,i=n.RGBA,o=e.RGBA,l=4,c=4,h=null!=t?t.HALF_FLOAT_OES:null,p=e.FLOAT,u=e.RGBA),{internalFormatFloat:r,internalFormatHalfFloat:s,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:u,downloadUnpackNumChannels:l,defaultNumChannels:c,textureTypeHalfFloat:h,textureTypeFloat:p}}!function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"}(tD||(tD={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(nD||(nD={})),function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(rD||(rD={}));var uD=n(96763);function lD(e,t){const n=t();return Ye().getBool("DEBUG")&&function(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+dD(e,t))}(e),n}const cD=5.96e-8,hD=65504;function pD(e){return!!(Ye().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||cD<Math.abs(e)&&Math.abs(e)<hD)}function dD(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}function fD(e,t){return PD(e,(()=>e.getExtension(t)),'Extension "'+t+'" not supported on this browser.')}function mD(e,t){const n=PD(e,(()=>e.createShader(e.VERTEX_SHADER)),"Unable to create vertex WebGLShader.");if(lD(e,(()=>e.shaderSource(n,t))),lD(e,(()=>e.compileShader(n))),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw uD.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function gD(e,t){const n=PD(e,(()=>e.createShader(e.FRAGMENT_SHADER)),"Unable to create fragment WebGLShader.");if(lD(e,(()=>e.shaderSource(n,t))),lD(e,(()=>e.compileShader(n))),Ye().get("ENGINE_COMPILE_ONLY"))return n;if(!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw bD(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}const yD=/ERROR: [0-9]+:([0-9]+):/g;function bD(e,t){const n=yD.exec(t);if(null==n)return uD.log(`Couldn't parse line number in error: ${t}`),void uD.log(e);const r=+n[1],s=e.split("\n"),a=s.length.toString().length+2,i=s.map(((e,t)=>ye((t+1).toString(),a)+e));let o=0;for(let e=0;e<i.length;e++)o=Math.max(i[e].length,o);const u=i.slice(0,r-1),l=i.slice(r-1,r),c=i.slice(r);uD.log(u.join("\n")),uD.log(t.split("\n")[0]),uD.log(`%c ${ye(l[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),uD.log(c.join("\n"))}function xD(e){return PD(e,(()=>e.createProgram()),"Unable to create WebGLProgram.")}function wD(e,t){if(lD(e,(()=>e.linkProgram(t))),!Ye().get("ENGINE_COMPILE_ONLY")&&!1===e.getProgramParameter(t,e.LINK_STATUS))throw uD.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function vD(e,t){if(lD(e,(()=>e.validateProgram(t))),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw uD.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function kD(e,t){const n=PD(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return lD(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),lD(e,(()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW))),n}function ID(e,t){const n=PD(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return lD(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n))),lD(e,(()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW))),n}function ND(){return 2===Ye().getNumber("WEBGL_VERSION")?1:4}function SD(e){return PD(e,(()=>e.createTexture()),"Unable to create WebGLTexture.")}function TD(e,t){const n=Ye().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0)throw new Error(`Requested texture size [${e}x${t}] is invalid.`);if(e>n||t>n)throw new Error(`Requested texture size [${e}x${t}] greater than WebGL maximum on this browser / GPU [${n}x${n}].`)}function CD(e){return PD(e,(()=>e.createFramebuffer()),"Unable to create WebGLFramebuffer.")}function $D(e,t,n,r,s,a,i){const o=e.getAttribLocation(t,n);return-1!==o&&(lD(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,r))),lD(e,(()=>e.vertexAttribPointer(o,s,e.FLOAT,!1,a,i))),lD(e,(()=>e.enableVertexAttribArray(o))),!0)}function ED(e,t,n){BD(e,n),lD(e,(()=>e.activeTexture(e.TEXTURE0+n))),lD(e,(()=>e.bindTexture(e.TEXTURE_2D,t)))}function AD(e,t){BD(e,t),lD(e,(()=>e.activeTexture(e.TEXTURE0+t))),lD(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}function RD(e,t,n){return PD(e,(()=>e.getUniformLocation(t,n)),'uniform "'+n+'" not present in program.')}function OD(e,t,n){return e.getUniformLocation(t,n)}function FD(e,t,n,r){lD(e,(()=>ED(e,t,r))),lD(e,(()=>e.uniform1i(n,r)))}function _D(e){lD(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),lD(e,(()=>e.viewport(0,0,e.canvas.width,e.canvas.height))),lD(e,(()=>e.scissor(0,0,e.canvas.width,e.canvas.height)))}function DD(e,t,n){lD(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,n))),lD(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)))}function MD(e,t){lD(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,t))),lD(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)))}function LD(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+zD(e,t))}function zD(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function PD(e,t,n){const r=lD(e,(()=>t()));if(null==r)throw new Error(n);return r}function BD(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n)throw new Error(`textureUnit must be in [gl.TEXTURE0, gl.TEXTURE${n}].`)}function WD(e,t=2){return le(e.slice(0,e.length-t))}function UD(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function VD(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[WD(e),...UD(e)]),t}function GD(e,t=!1){let n=Ye().getNumber("WEBGL_MAX_TEXTURE_SIZE"),r=Ye().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");if(r===1/0&&Ye().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(r=n/2),t&&(n*=2,r*=2,1===(e=e.map(((t,n)=>n>=e.length-2?te(e[n]):e[n]))).length&&(e=[2,e[0]])),2!==e.length){const t=ve(e);e=t.newShape}let s=le(e),a=null;e.length<=1&&s<=n?a=[1,s]:2===e.length&&e[0]<=n&&e[1]<=n?a=e:3===e.length&&e[0]*e[1]<=n&&e[2]<=n?a=[e[0]*e[1],e[2]]:3===e.length&&e[0]<=n&&e[1]*e[2]<=n?a=[e[0],e[1]*e[2]]:4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n?a=[e[0]*e[1]*e[2],e[3]]:4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n&&(a=[e[0],e[1]*e[2]*e[3]]);const i=null!=a&&Math.max(...a)>r&&Math.min(...a)<=(t?2:1)&&Math.min(...a)>0;if(null==a||i)if(t){const t=WD(e);let n=2,r=2;e.length&&([n,r]=UD(e)),s=t*(n/2)*(r/2),a=me(s).map((e=>2*e))}else a=me(s);return a}function jD(e){return e%2==0}function HD(e,t){if(pe(e=e.slice(-2),t=t.slice(-2)))return!0;if(!e.length||!t.length)return!0;if(0===e[0]||0===e[1]||0===t[0]||0===t[1])return!0;if(e.length!==t.length){const n=e[e.length-1],r=t[t.length-1];if(n===r)return!0;if(jD(n)&&jD(r)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&jD(e[0])&&jD(t[0])}let qD,KD;function XD(e){if(null==qD){const t=eD(e);qD=t.getParameter(t.MAX_TEXTURE_SIZE)}return qD}function YD(){qD=null}function JD(){KD=null}function ZD(e){if(null==KD){const t=eD(e);KD=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,KD)}function QD(e){if(0===e)return 0;let t;const n=eD(e);return t=eM(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:eM(n,"EXT_disjoint_timer_query")?1:0,t}function eM(e,t){return null!=e.getExtension(t)}function tM(e){try{if(null!=eD(e))return!0}catch(e){return uD.log("Error when getting WebGL context: ",e),!1}return!1}function nM(e){if(0===e)return!1;const t=eD(e);if(1===e){if(!eM(t,"OES_texture_float"))return!1}else if(!eM(t,"EXT_color_buffer_float"))return!1;return sM(t)}function rM(e){if(0===e)return!1;const t=eD(e);if(1!==e){if(eM(t,"EXT_color_buffer_float"))return sM(t);const e="EXT_color_buffer_half_float";if(eM(t,e)){const n=t.getExtension(e);return function(e,t){const n=oD(e,t),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r);e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);const s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(s),a}(t,n)}return!1}return!!eM(t,"OES_texture_float")&&(!!eM(t,"WEBGL_color_buffer_float")&&sM(t))}function sM(e){const t=oD(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const s=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(r),s}function aM(e){return 2===e&&null!=eD(e).fenceSync}function iM(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&ie("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the WebGL backend.`))}))}const oM=Ye();function uM(){let e,t,n,r,s,a,i,o,u,l;return 2===Ye().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",r="in",s="texture",a="outputColor",i="out vec4 outputColor;",o=Ye().getBool("WEBGL2_ISNAN_CUSTOM")?"\n bool isnan_custom(float val) {\n uint floatToUint = floatBitsToUint(val);\n return (floatToUint & 0x7fffffffu) > 0x7f800000u;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ":"",u="",l="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(e="",t="attribute",n="varying",r="varying",s="texture2D",a="gl_FragColor",i="",o="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",u="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",l="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:s,output:a,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:u,defineRound:l}}function lM(e,t,n="index"){const r=De(t);return r.map(((t,s)=>`int ${e[s]} = ${n} / ${t}; ${s===r.length-1?`int ${e[s+1]} = ${n} - ${e[s]} * ${t}`:`index -= ${e[s]} * ${t}`};`)).join("")}function cM(e,t,n="index"){const r=De(t);return r.map(((t,s)=>`int ${e[s]} = ${n} / outShapeStrides[${s}]; ${s===r.length-1?`int ${e[s+1]} = ${n} - ${e[s]} * outShapeStrides[${s}]`:`index -= ${e[s]} * outShapeStrides[${s}]`};`)).join("")}function hM(e){const t=De(e).map((e=>e.toString()));return`\n int getFlatIndex(ivec3 coords) {\n return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;\n }\n`}oM.registerFlag("HAS_WEBGL",(()=>oM.getNumber("WEBGL_VERSION")>0)),oM.registerFlag("WEBGL_VERSION",(()=>tM(2)?2:tM(1)?1:0)),oM.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",(()=>!1)),oM.registerFlag("WEBGL_BUFFER_SUPPORTED",(()=>2===oM.get("WEBGL_VERSION"))),oM.registerFlag("WEBGL_CPU_FORWARD",(()=>!0)),oM.registerFlag("WEBGL_FORCE_F16_TEXTURES",(()=>!1)),oM.registerFlag("WEBGL_PACK",(()=>oM.getBool("HAS_WEBGL"))),oM.registerFlag("WEBGL_PACK_NORMALIZATION",(()=>oM.getBool("WEBGL_PACK"))),oM.registerFlag("WEBGL_PACK_CLIP",(()=>oM.getBool("WEBGL_PACK"))),oM.registerFlag("WEBGL_PACK_DEPTHWISECONV",(()=>oM.getBool("WEBGL_PACK"))),oM.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(()=>oM.getBool("WEBGL_PACK"))),oM.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(()=>oM.getBool("WEBGL_PACK"))),oM.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(()=>oM.getBool("WEBGL_PACK"))),oM.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(()=>oM.getBool("WEBGL_PACK"))),oM.registerFlag("WEBGL_PACK_REDUCE",(()=>oM.getBool("WEBGL_PACK"))),oM.registerFlag("WEBGL_LAZILY_UNPACK",(()=>oM.getBool("WEBGL_PACK"))),oM.registerFlag("WEBGL_CONV_IM2COL",(()=>oM.getBool("WEBGL_PACK"))),oM.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",(()=>oM.getBool("WEBGL_PACK"))),oM.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(()=>XD(oM.getNumber("WEBGL_VERSION")))),oM.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(()=>ZD(oM.getNumber("WEBGL_VERSION")))),oM.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(()=>{const e=oM.getNumber("WEBGL_VERSION");return 0===e?0:QD(e)})),oM.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(()=>oM.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!qa())),oM.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(()=>nM(oM.getNumber("WEBGL_VERSION")))),oM.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(()=>!oM.getBool("WEBGL_FORCE_F16_TEXTURES")&&oM.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))),oM.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(()=>rM(oM.getNumber("WEBGL_VERSION")))),oM.registerFlag("WEBGL_FENCE_API_ENABLED",(()=>aM(oM.getNumber("WEBGL_VERSION")))),oM.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(()=>oM.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0)),oM.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",(()=>-1),(e=>{if("number"!=typeof e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${e}.`);if(e<0&&-1!==e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)})),oM.registerFlag("WEBGL_FLUSH_THRESHOLD",(()=>qa()?1:-1),(e=>{if("number"!=typeof e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${e}.`);if(e<0&&-1!==e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)})),oM.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",(()=>128)),oM.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",(()=>!1)),oM.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",(()=>1e5)),oM.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",(()=>128)),oM.registerFlag("WEBGL_EXP_CONV",(()=>!1)),oM.registerFlag("SOFTWARE_WEBGL_ENABLED",(()=>oM.getBool("IS_TEST"))),oM.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",(()=>1/0)),oM.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",(()=>!1)),oM.registerFlag("WEBGL2_ISNAN_CUSTOM",(()=>!1)),oM.registerFlag("ENGINE_COMPILE_ONLY",(()=>!1));const pM="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n",{getBroadcastDims:dM}=y;function fM(e,t,n){const r=[];if(e.forEach((e=>{const t=le(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform?r.push(`uniform float ${e.name}${t>1?`[${t}]`:""};`):(r.push(`uniform sampler2D ${e.name};`),r.push(`uniform int offset${e.name};`)),n.enableShapeUniforms){const{uniformShape:t}=NM(n.packedInputs,e.shapeInfo.logicalShape,e.shapeInfo.texShape);switch(t.length){case 1:r.push(`uniform int ${e.name}Shape;`);break;case 2:r.push(`uniform ivec2 ${e.name}Shape;`);break;case 3:r.push(`uniform ivec3 ${e.name}Shape;`);break;case 4:r.push(`uniform ivec4 ${e.name}Shape;`)}r.push(`uniform ivec2 ${e.name}TexShape;`)}})),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:r.push("uniform int outShape;");break;case 2:r.push("uniform ivec2 outShape;"),r.push("uniform int outShapeStrides;");break;case 3:r.push("uniform ivec3 outShape;"),r.push("uniform ivec2 outShapeStrides;");break;case 4:r.push("uniform ivec4 outShape;"),r.push("uniform ivec3 outShapeStrides;")}r.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach((e=>{r.push(`uniform ${e.type} ${e.name}${e.arrayIndex?`[${e.arrayIndex}]`:""};`)}));const s=r.join("\n"),a=e.map((e=>function(e,t,n=!1,r){let s="";s+=n?gM(e,r):mM(e,r);const a=e.shapeInfo.logicalShape,i=t.logicalShape;return a.length<=i.length&&(s+=n?function(e,t){const n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=dM(e.shapeInfo.logicalShape,t.logicalShape),u=IM(i),l=i-a;let c;const h=["x","y","z","w","u","v"];c=0===a?"":i<2&&o.length>=1?"coords = 0;":o.map((e=>`coords.${h[e+l]} = 0;`)).join("\n");let p="";p=i<2&&a>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${h[t+l]}`)).join(", ");let d="return outputValue;";const f=1===le(e.shapeInfo.logicalShape),m=1===le(t.logicalShape);if(1!==a||f||m){if(f&&!m)d=1===i?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(o.length){const e=a-2,t=a-1;o.indexOf(e)>-1&&o.indexOf(t)>-1?d="return vec4(outputValue.x);":o.indexOf(e)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(t)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}}else d="\n return vec4(outputValue.xy, outputValue.xy);\n ";return`\n vec4 ${s}() {\n ${u} coords = getOutputCoords();\n ${c}\n vec4 outputValue = get${r}(${p});\n ${d}\n }\n `}(e,t):function(e,t){const n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,u=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===u&&null==e.shapeInfo.flatOffset&&pe(i,a))return`\n float ${s}() {\n return sampleTexture(${n}, resultUV);\n }\n `;const l=IM(u),c=dM(e.shapeInfo.logicalShape,t.logicalShape),h=u-o;let p;const d=["x","y","z","w","u","v"];p=0===o?"":u<2&&c.length>=1?"coords = 0;":c.map((e=>`coords.${d[e+h]} = 0;`)).join("\n");let f="";return f=u<2&&o>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${d[t+h]}`)).join(", "),`\n float ${s}() {\n ${l} coords = getOutputCoords();\n ${p}\n return get${r}(${f});\n }\n `}(e,t)),s}(e,t,n.packedInputs,n.enableShapeUniforms))).join("\n"),i=t.texShape,o=uM(),u=function(e){return`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${e.texture2D}(textureSampler, uv).r;\n }\n `}(o);let l,c,h=function(e){return`${e.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${e.varyingFs} vec2 resultUV;\n ${e.defineOutput}\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n ${e.defineSpecialNaN}\n ${e.defineSpecialInf}\n ${e.defineRound}\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n ${yM}\n ${bM}\n ${xM}\n `}(o);return t.isPacked?(l=function(e,t,n){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t,n){const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return 1===r[0]?n?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));\n }\n ":`\n int getOutputCoords() {\n return 2 * int(resultUV.x * ${r[1]}.0);\n }\n `:1===r[1]?n?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));\n }\n ":`\n int getOutputCoords() {\n return 2 * int(resultUV.y * ${r[0]}.0);\n }\n `:n?"\n int getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);\n }\n ":`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n return 2 * (resTexRC.x * ${r[1]} + resTexRC.y);\n }\n `}(0,t,n);case 2:return function(e,t,n){const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(pe(e,t))return n?"\n ivec2 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));\n }\n ":`\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2(${r[0]}, ${r[1]}));\n }\n `;const s=Math.ceil(e[1]/2);return n?"\n ivec2 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec2(r, c);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n int r = 2 * (index / ${s});\n int c = imod(index, ${s}) * 2;\n\n return ivec2(r, c);\n }\n `}(e,t,n);case 3:return function(e,t,n){if(n)return"\n ivec3 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));\n int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n int b = index / texelsInBatch;\n index -= b * texelsInBatch;\n\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec3(b, r, c);\n }\n ";const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[2]/2),a=s*Math.ceil(e[1]/2);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n\n int b = index / ${a};\n index -= b * ${a};\n\n int r = 2 * (index / ${s});\n int c = imod(index, ${s}) * 2;\n\n return ivec3(b, r, c);\n }\n `}(e,t,n);default:return function(e,t,n){if(n)return"\n ivec4 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));\n int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));\n int texelsInBatchN = texelsInBatch * outShape[1];\n\n int b2 = index / texelsInBatchN;\n index -= b2 * texelsInBatchN;\n\n int b = index / texelsInBatch;\n index -= b * texelsInBatch;\n\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec4(b2, b, r, c);\n }\n ";const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),a=s*Math.ceil(e[e.length-2]/2);let i=a,o="",u="b, r, c";for(let t=2;t<e.length-1;t++)i*=e[e.length-t-1],o=`\n int b${t} = index / ${i};\n index -= b${t} * ${i};\n `+o,u=`b${t}, `+u;return`\n ivec${e.length} getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n\n ${o}\n\n int b = index / ${a};\n index -= b * ${a};\n\n int r = 2 * (index / ${s});\n int c = imod(index, ${s}) * 2;\n\n return ivec${e.length}(${u});\n }\n `}(e,t,n)}}(t.logicalShape,i,n.enableShapeUniforms),c=function(e){return`\n void setOutput(vec4 val) {\n ${e.output} = val;\n }\n `}(o)):(l=function(e,t,n){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t,n){return 1===t[0]?n?"\n int getOutputCoords() {\n return int(resultUV.x * float(outTexShape[1]));\n }\n ":`\n int getOutputCoords() {\n return int(resultUV.x * ${t[1]}.0);\n }\n `:1===t[1]?n?"\n int getOutputCoords() {\n return int(resultUV.y * float(outTexShape[0]));\n }\n ":`\n int getOutputCoords() {\n return int(resultUV.y * ${t[0]}.0);\n }\n `:n?"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n return resTexRC.x * outTexShape[1] + resTexRC.y;\n }\n ":`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n return resTexRC.x * ${t[1]} + resTexRC.y;\n }\n `}(0,t,n);case 2:return function(e,t,n){return pe(e,t)?n?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));\n }\n ":`\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));\n }\n `:1===e[1]?n?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n return ivec2(index, 0);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n return ivec2(index, 0);\n }\n `:1===e[0]?n?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n return ivec2(0, index);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n return ivec2(0, index);\n }\n `:n?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n int r = index / outShape[1];\n int c = index - r * outShape[1];\n return ivec2(r, c);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n int r = index / ${e[1]};\n int c = index - r * ${e[1]};\n return ivec2(r, c);\n }\n `}(e,t,n);case 3:return function(e,t,n){if(n)return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n ${cM(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n`;const r=lM(["r","c","d"],e);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n ${r}\n return ivec3(r, c, d);\n }\n `}(e,t,n);case 4:return function(e,t,n){if(n)return`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n ${cM(["r","c","d","d2"],e)}\n return ivec4(r, c, d, d2);\n }\n `;const r=lM(["r","c","d","d2"],e);return`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n ${r}\n return ivec4(r, c, d, d2);\n }\n `}(e,t,n);case 5:return function(e,t){const n=lM(["r","c","d","d2","d3"],e);return`\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},\n ${t[1]}));\n\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n\n ${n}\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n `}(e,t);case 6:return function(e,t){const n=lM(["r","c","d","d2","d3","d4"],e);return`\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n\n ${n}\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n `}(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}(t.logicalShape,i,n.enableShapeUniforms),c=function(e){return`\n void setOutput(float val) {\n ${e.output} = vec4(val, 0, 0, 0);\n }\n `}(o)),n.packedInputs&&(h+=wM),[h,u,c,s,l,a,n.userCode].join("\n")}function mM(e,t=!1){const n=e.shapeInfo.logicalShape;switch(n.length){case 0:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${r}() {return ${n};}`;const[s,a]=e.shapeInfo.texShape;if(1===s&&1===a)return`\n float ${r}() {\n return sampleTexture(${n}, halfCR);\n }\n `;const i=vM(n);if(t)return`\n float ${r}() {\n vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${i});\n return sampleTexture(${n}, uv);\n }\n `;const[o,u]=e.shapeInfo.texShape;return`\n float ${r}() {\n vec2 uv = uvFromFlat(${o}, ${u}, ${i});\n return sampleTexture(${n}, uv);\n }\n `}(e,t);case 1:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`\n float ${r}(int index) {\n ${kM(e)}\n }\n `;const s=e.shapeInfo.texShape,a=s[0],i=s[1];if(1===i&&1===a)return`\n float ${r}(int index) {\n return sampleTexture(${n}, halfCR);\n }\n `;const o=vM(n);return 1===i?t?`\n float ${r}(int index) {\n vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / float(${n}TexShape[0]));\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int index) {\n vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${a}.0);\n return sampleTexture(${n}, uv);\n }\n `:1===a?t?`\n float ${r}(int index) {\n vec2 uv = vec2((float(index + ${o}) + 0.5) / float(${n}TexShape[1]), 0.5);\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int index) {\n vec2 uv = vec2((float(index + ${o}) + 0.5) / ${i}.0, 0.5);\n return sampleTexture(${n}, uv);\n }\n `:t?`\n float ${r}(int index) {\n vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${o});\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int index) {\n vec2 uv = uvFromFlat(${a}, ${i}, index + ${o});\n return sampleTexture(${n}, uv);\n }\n `}(e,t);case 2:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape;if(null!=a&&pe(n,a)){if(t)return`\n float ${s}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `;const e=a[0];return`\n float ${s}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${a[1]}.0, ${e}.0);\n return sampleTexture(${r}, uv);\n }\n `}const{newShape:i,keptDims:o}=ve(n),u=i;if(u.length<n.length){const n=["row","col"];return`\n ${mM(SM(e,u),t)}\n float ${s}(int row, int col) {\n return ${s}(${TM(n,o)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${s}(int row, int col) {\n int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));\n ${kM(e)}\n }\n `;const l=a[0],c=a[1],h=vM(r);return 1===c?t?`\n float ${s}(int row, int col) {\n float index = dot(vec3(row, col, ${h}), vec3(${r}Shape[1], 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / float(${r}TexShape[0]));\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${s}(int row, int col) {\n float index = dot(vec3(row, col, ${h}), vec3(${n[1]}, 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);\n return sampleTexture(${r}, uv);\n }\n `:1===l?t?`\n float ${s}(int row, int col) {\n float index = dot(vec3(row, col, ${h}), vec3(${r}Shape[1], 1, 1));\n vec2 uv = vec2((index + 0.5) / float(${r}TexShape[1]), 0.5);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${s}(int row, int col) {\n float index = dot(vec3(row, col, ${h}), vec3(${n[1]}, 1, 1));\n vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);\n return sampleTexture(${r}, uv);\n }\n `:t?`\n float ${s}(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${r}Shape[1] + col + ${h};\n vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${s}(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${n[1]} + col + ${h};\n vec2 uv = uvFromFlat(${l}, ${c}, index);\n return sampleTexture(${r}, uv);\n }\n`}(e,t);case 3:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[1]*n[2],i=n[2],{newShape:o,keptDims:u}=ve(n),l=o;if(l.length<n.length){const n=["row","col","depth"];return`\n ${mM(SM(e,l),t)}\n float ${s}(int row, int col, int depth) {\n return ${s}(${TM(n,u)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${s}(int row, int col, int depth) {\n int index = round(dot(vec3(row, col, depth),\n vec3(${a}, ${i}, 1)));\n ${kM(e)}\n }\n `;const c=e.shapeInfo.texShape,h=c[0],p=c[1],d=e.shapeInfo.flatOffset;if(p===a&&null==d)return t?`\n float ${s}(int row, int col, int depth) {\n int stride1 = ${r}Shape[2];\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2(stride1, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${s}(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2(${i}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${p}.0, ${h}.0);\n return sampleTexture(${r}, uv);\n }\n `;if(p===i&&null==d)return t?`\n float ${s}(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2(${r}Shape[1], 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${s}(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2(${n[1]}, 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}.0, ${h}.0);\n return sampleTexture(${r}, uv);\n }\n `;const f=vM(r);return t?`\n float ${s}(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int stride0 = ${r}Shape[1] * ${r}Shape[2];\n int stride1 = ${r}Shape[2];\n int index = row * stride0 + col * stride1 + depth + ${f};\n vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${s}(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${a} + col * ${i} + depth + ${f};\n vec2 uv = uvFromFlat(${h}, ${p}, index);\n return sampleTexture(${r}, uv);\n }\n `}(e,t);case 4:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[3],i=n[2]*a,o=n[1]*i,{newShape:u,keptDims:l}=ve(n);if(u.length<n.length){const n=["row","col","depth","depth2"];return`\n ${mM(SM(e,u),t)}\n float ${s}(int row, int col, int depth, int depth2) {\n return ${s}(${TM(n,l)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${s}(int row, int col, int depth, int depth2) {\n int index = round(dot(vec4(row, col, depth, depth2),\n vec4(${o}, ${i}, ${a}, 1)));\n ${kM(e)}\n }\n `;const c=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,p=h[0],d=h[1],f=`int stride2 = ${r}Shape[3];`,m=`int stride1 = ${r}Shape[2] * stride2;`,g=`int stride0 = ${r}Shape[1] * stride1;`;if(d===o&&null==c)return t?`\n float ${s}(int row, int col, int depth, int depth2) {\n ${f}\n ${m}\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3(stride1, stride2, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${s}(int row, int col, int depth, int depth2) {\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3(${i}, ${a}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${d}.0, ${p}.0);\n return sampleTexture(${r}, uv);\n }\n `;if(d===a&&null==c)return t?`\n float ${s}(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3(${r}Shape[1] * ${r}Shape[2], ${r}Shape[2], 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${s}(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3(${n[1]*n[2]}, ${n[2]}, 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${d}.0, ${p}.0);\n return sampleTexture(${r}, uv);\n }\n `;const y=vM(r);return t?`\n float ${s}(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n ${f}\n ${m}\n ${g}\n int index = row * stride0 + col * stride1 +\n depth * stride2 + depth2;\n vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index + ${y});\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${s}(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${o} + col * ${i} +\n depth * ${a} + depth2;\n vec2 uv = uvFromFlat(${p}, ${d}, index + ${y});\n return sampleTexture(${r}, uv);\n }\n `}(e,t);case 5:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=t[4],a=t[3]*s,i=t[2]*a,o=t[1]*i,{newShape:u,keptDims:l}=ve(t);if(u.length<t.length){const t=["row","col","depth","depth2","depth3"];return`\n ${mM(SM(e,u))}\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n return ${r}(${TM(t,l)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n float index = dot(\n vec4(row, col, depth, depth2),\n vec4(${o}, ${i}, ${a}, ${s})) +\n depth3;\n ${kM(e)}\n }\n `;const c=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,p=h[0],d=h[1];if(d===o&&null==c)return`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(${i}, ${a}, ${s}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${d}.0, ${p}.0);\n return sampleTexture(${n}, uv);\n }\n `;if(d===s&&null==c)return`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n float texR = dot(\n vec4(row, col, depth, depth2),\n vec4(${t[1]*t[2]*t[3]},\n ${t[2]*t[3]}, ${t[3]}, 1));\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${d}.0, ${p}.0);\n return sampleTexture(${n}, uv);\n }\n `;return`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${o} + col * ${i} + depth * ${a} +\n depth2 * ${s} + depth3 + ${vM(n)};\n vec2 uv = uvFromFlat(${p}, ${d}, index);\n return sampleTexture(${n}, uv);\n }\n `}(e);case 6:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:s,keptDims:a}=ve(t);if(s.length<t.length){const t=["row","col","depth","depth2","depth3","depth4"];return`\n ${mM(SM(e,s))}\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return ${r}(${TM(t,a)});\n }\n `}const i=t[5],o=t[4]*i,u=t[3]*o,l=t[2]*u,c=t[1]*l;if(e.shapeInfo.isUniform)return`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = round(dot(\n vec4(row, col, depth, depth2),\n vec4(${c}, ${l}, ${u}, ${o})) +\n dot(\n vec2(depth3, depth4),\n vec2(${i}, 1)));\n ${kM(e)}\n }\n `;const h=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,d=p[0],f=p[1];if(f===c&&null==h)return`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(${l}, ${u}, ${o}, ${i})) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${f}.0, ${d}.0);\n return sampleTexture(${n}, uv);\n }\n `;if(f===i&&null==h)return`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n float texR = dot(vec4(row, col, depth, depth2),\n vec4(${t[1]*t[2]*t[3]*t[4]},\n ${t[2]*t[3]*t[4]},\n ${t[3]*t[4]},\n ${t[4]})) + float(depth3);\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${f}.0, ${d}.0);\n return sampleTexture(${n}, uv);\n }\n `;return`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${c} + col * ${l} + depth * ${u} +\n depth2 * ${o} + depth3 * ${i} + depth4 + ${vM(n)};\n vec2 uv = uvFromFlat(${d}, ${f}, index);\n return sampleTexture(${n}, uv);\n }\n `}(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function gM(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return function(e){const t=e.name;return`\n vec4 ${"get"+t.charAt(0).toUpperCase()+t.slice(1)}() {\n return ${uM().texture2D}(${t}, halfCR);\n }\n `}(e);case 1:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,a=uM();if(t)return`\n vec4 ${r}(int index) {\n ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\n vec2 uv = packedUVfrom1D(\n packedTexShape[0], packedTexShape[1], index);\n return ${a.texture2D}(${n}, uv);\n }\n `;const i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];return`\n vec4 ${r}(int index) {\n vec2 uv = packedUVfrom1D(\n ${i[0]}, ${i[1]}, index);\n return ${a.texture2D}(${n}, uv);\n }\n `}(e,t);case 2:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,i=a[0],o=a[1],u=uM();if(null!=a&&pe(n,a))return t?`\n vec4 ${s}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n\n return ${u.texture2D}(${r}, uv);\n }\n `:`\n vec4 ${s}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${i}.0);\n\n return ${u.texture2D}(${r}, uv);\n }\n `;if(t)return`\n vec4 ${s}(int row, int col) {\n ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));\n int valuesPerRow = int(ceil(float(${r}Shape[1]) / 2.0));\n vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);\n return ${u.texture2D}(${r}, uv);\n }\n `;const l=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];return`\n vec4 ${s}(int row, int col) {\n vec2 uv = packedUVfrom2D(${Math.ceil(n[1]/2)}, ${l[0]}, ${l[1]}, row, col);\n return ${u.texture2D}(${r}, uv);\n }\n `}(e,t);case 3:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(1===n[0]){const r=[1,2],a=["b","row","col"];return`\n ${gM(SM(e,n.slice(1)),t)}\n vec4 ${s}(int b, int row, int col) {\n return ${s}(${TM(a,r)});\n }\n `}const o=uM();if(t)return`\n vec4 ${s}(int b, int row, int col) {\n ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));\n int valuesPerRow = int(ceil(float(${r}Shape[2]) / 2.0));\n int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[1]) / 2.0));\n vec2 uv = packedUVfrom3D(\n packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);\n return ${o.texture2D}(${r}, uv);\n }\n `;const u=i[0],l=i[1],c=Math.ceil(n[2]/2);return`\n vec4 ${s}(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n ${u}, ${l}, ${c*Math.ceil(n[1]/2)}, ${c}, b, row, col);\n return ${o.texture2D}(${r}, uv);\n }\n `}(e,t);default:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=uM();if(t)return`\n vec4 ${r}(int b2, int b, int row, int col) {\n int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));\n int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));\n int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);\n texelsInBatch *= ${n}Shape[1];\n index = b2 * texelsInBatch + index;\n ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\n int texR = index / packedTexShape[1];\n int texC = index - texR * packedTexShape[1];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${s.texture2D}(${n}, uv);\n }\n `;const a=e.shapeInfo.logicalShape,i=a.length,o=e.shapeInfo.texShape,u=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],l=u[0],c=u[1],h=Math.ceil(a[i-1]/2);let p=h*Math.ceil(a[i-2]/2),d="int b, int row, int col",f=`b * ${p} + (row / 2) * ${h} + (col / 2)`;for(let e=2;e<i-1;e++)d=`int b${e}, `+d,p*=a[i-e-1],f=`b${e} * ${p} + `+f;return`\n vec4 ${r}(${d}) {\n int index = ${f};\n int texR = index / ${c};\n int texC = index - texR * ${c};\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}, ${l});\n return ${s.texture2D}(${n}, uv);\n }\n `}(e,t)}}const yM="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",bM="\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",xM="\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",wM="\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n";function vM(e){return`offset${e}`}function kM(e){const t=e.name,n=le(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`\n for (int i = 0; i < ${n}; i++) {\n if (i == index) {\n return ${t}[i];\n }\n }\n `}function IM(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function NM(e,t,n){const{newShape:r,keptDims:s}=ve(t),a=t.length,i=e&&3===a&&1===t[0],o=i?t.slice(1):r,u=!e&&a>1&&!pe(t,n)&&r.length<a||i;return{useSqueezeShape:u,uniformShape:u?o:t,keptDims:s}}function SM(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function TM(e,t){return t.map((t=>e[t])).join(", ")}function CM(e,t,n){const r=[],s=[];let a,i,o,u=null,l=null;l=e.getUniformLocation(n,"NAN",!1),1===Ye().getNumber("WEBGL_VERSION")&&(u=e.getUniformLocation(n,"INFINITY",!1));const c=!1;for(const s of t.variableNames){const a={name:s,uniform:e.getUniformLocation(n,s,c),offset:e.getUniformLocation(n,`offset${s}`,c)};t.enableShapeUniforms&&(a.shape=e.getUniformLocation(n,`${s}Shape`,c),a.texShape=e.getUniformLocation(n,`${s}TexShape`,c)),r.push(a)}if(t.enableShapeUniforms&&(a=e.getUniformLocation(n,"outShape",c),o=e.getUniformLocation(n,"outShapeStrides",c),i=e.getUniformLocation(n,"outTexShape",c)),t.customUniforms)for(const r of t.customUniforms)s.push(e.getUniformLocation(n,r.name,c));return{variablesLocations:r,customUniformLocations:s,infLoc:u,nanLoc:l,outShapeLocation:a,outShapeStridesLocation:o,outTexShapeLocation:i}}function $M(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach(((e,n)=>{const r=e.logicalShape,s=t[n],a=s.shape;if(!pe(r,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${a} must match`);if(e.isUniform&&s.isUniform)return;const i=e.texShape,o=s.isUniform?null:s.texData.texShape;if(!pe(i,o))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${o} must match`)}))}function EM(e){return Ye().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}class AM{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=tD.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=uM();this.outputShape=e,this.enableShapeUniforms=EM(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?cM(["r","c","d"],e):lM(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n ${t.output} = result;\n }\n `}}class RM{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=tD.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=uM();this.outputShape=e,this.enableShapeUniforms=EM(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?cM(["r","c","d"],e):lM(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n ${t.output} = result;\n }\n `}}class OM{constructor(e){this.variableNames=["A"],this.outTexUsage=nD.DOWNLOAD;const t=uM();this.outputShape=e,this.userCode=`\n ${pM}\n\n void main() {\n float x = getAAtOutCoords();\n ${t.output} = encode_float(x);\n }\n `}}class FM{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=nD.DOWNLOAD;const t=uM();this.outputShape=e,this.userCode=`\n ${pM}\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n ${t.output} = encode_float(x);\n }\n `}}const _M={R:0,G:1,B:2,A:3};class DM{constructor(e,t=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const r=uM();this.outputShape=e,this.enableShapeUniforms=EM(this.outputShape.length);let s="result";t&&(s="floor(result * 255. + 0.5)");let a="";for(let e=0;e<n.length;e++){const t=n[e];a+=`\n if(offset == ${e}) {\n result = values[${_M[t]}];\n }`}this.userCode=`\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":hM(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n int flatIndex = getFlatIndex(coords);\n float result = 0.;\n int offset = imod(flatIndex, ${n.length});\n\n flatIndex = idiv(flatIndex, ${n.length}, 1.);\n\n int r = flatIndex / texShape[1];\n if (r < texShape[0]) {\n int c = imod(flatIndex, texShape[1]);\n vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n vec4 values = ${r.texture2D}(A, uv);\n ${a}\n }\n ${r.output} = vec4(${s}, 0., 0., 0.);\n }\n `}}class MM{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=uM();this.outputShape=e,this.enableShapeUniforms=EM(this.outputShape.length);let r="",s="result";t&&(s="floor(result * 255. + 0.5)");for(let t=0;t<=1;t++)for(let s=0;s<=1;s++){const a=2*t+s;r+=`\n localCoords = coords;\n if(localCoords[2] + ${s} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {\n localCoords[2] += ${s};\n if (localCoords[1] + ${t} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {\n localCoords[1] += ${t};\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n int r = flatIndex / texShape[1];\n int c = imod(flatIndex, texShape[1]);\n vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n values = ${n.texture2D}(A, uv);\n\n if (offset == 0) {\n result[${a}] = values[0];\n } else if (offset == 1) {\n result[${a}] = values[1];\n } else if (offset == 2) {\n result[${a}] = values[2];\n } else {\n result[${a}] = values[3];\n }\n }\n }\n `}this.userCode=`\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":hM(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n\n ${r}\n\n ${n.output} = ${s};\n }\n `}}function LM(e){const t=uM();return mD(e,`${t.version}\n precision highp float;\n ${t.attribute} vec3 clipSpacePos;\n ${t.attribute} vec2 uv;\n ${t.varyingVs} vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }`)}function zM(e){return kD(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function PM(e){return ID(e,new Uint16Array([0,1,2,2,1,3]))}function BM(e,t,n,r,s,a){TD(t,n);const i=SD(e),o=e.TEXTURE_2D;return lD(e,(()=>e.bindTexture(o,i))),lD(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE))),lD(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE))),lD(e,(()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST))),lD(e,(()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST))),1===Ye().getNumber("WEBGL_VERSION")?lD(e,(()=>e.texImage2D(o,0,r,t,n,0,s,a,null))):lD(e,(()=>e.texStorage2D(o,1,r,t,n))),lD(e,(()=>e.bindTexture(e.TEXTURE_2D,null))),{texture:i,texShape:[n,t]}}function WM(e){return e.internalFormatFloat}function UM(e,t,n,r){const[s,a]=sD(t,n);return BM(e,s,a,WM(r),r.textureFormatFloat,e.FLOAT)}function VM(e){return e.internalFormatHalfFloat}function GM(e,t,n,r){const[s,a]=sD(t,n);return BM(e,s,a,VM(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function jM(e){return e.downloadTextureFormat}function HM(e,t,n,r){const[s,a]=sD(t,n);return BM(e,s,a,jM(r),e.RGBA,e.UNSIGNED_BYTE)}function qM(e){return e.internalFormatPackedFloat}function KM(e,t,n,r){const[s,a]=iD(t,n);return BM(e,s,a,qM(r),e.RGBA,e.FLOAT)}function XM(e){return e.internalFormatPackedHalfFloat}function YM(e,t,n,r){const[s,a]=iD(t,n);return BM(e,s,a,XM(r),e.RGBA,r.textureTypeHalfFloat)}function JM(e,t,n){return lD(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),$D(e,t,"clipSpacePos",n,3,20,0)&&$D(e,t,"uv",n,2,20,12)}function ZM(e,t,n,r,s,a){let i,o,u;lD(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),s instanceof Uint8Array?(i=new Uint8Array(n*r*4),o=e.UNSIGNED_BYTE,u=e.RGBA):(i=new Float32Array(n*r*4),o=e.FLOAT,u=a.internalFormatPackedFloat),i.set(s),2===Ye().getNumber("WEBGL_VERSION")?lD(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGBA,o,i))):lD(e,(()=>e.texImage2D(e.TEXTURE_2D,0,u,n,r,0,e.RGBA,o,i))),lD(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}function QM(e,t,n){lD(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),n.data instanceof Uint8Array?2===Ye().getNumber("WEBGL_VERSION")?lD(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data))):lD(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data))):2===Ye().getNumber("WEBGL_VERSION")?lD(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n))):lD(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n))),lD(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}function eL(e,t,n,r){const s=e.createBuffer();lD(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,s)));const a=16*t*n;return lD(e,(()=>e.bufferData(e.PIXEL_PACK_BUFFER,a,e.STREAM_READ))),lD(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0))),lD(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null))),s}function tL(e,t,n){const r=e,s=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,s),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),s}function nL(e,t,n,r){const[s,a]=sD(t,n),i=new Uint8Array(t*n*4);return lD(e,(()=>e.readPixels(0,0,s,a,r.downloadTextureFormat,e.UNSIGNED_BYTE,i))),new Float32Array(i.buffer)}function rL(e,t,n,r,s,a,i,o){const u=e,l=new Float32Array(function(e,t){const[n,r]=iD(e,t);return n*r*4}(a,i));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}function sL(e,t,n){const r=new Float32Array(t*n*4);return lD(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r))),r}var aL=n(96763);class iL{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const t=Ye().getNumber("WEBGL_VERSION");if(null!=e?(this.gl=e,Q_(t,e)):this.gl=eD(t),e=this.gl,2===Ye().getNumber("WEBGL_VERSION")){const t=e;this.createVertexArray=()=>lD(t,(()=>t.createVertexArray())),this.bindVertexArray=e=>lD(t,(()=>t.bindVertexArray(e))),this.deleteVertexArray=e=>lD(t,(()=>t.deleteVertexArray(e))),this.getVertexArray=()=>lD(t,(()=>t.getParameter(t.VERTEX_ARRAY_BINDING)))}else if(null!=e){const t=e.getExtension("OES_vertex_array_object");if(null==t)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>lD(e,(()=>t.createVertexArrayOES())),this.bindVertexArray=n=>lD(e,(()=>t.bindVertexArrayOES(n))),this.deleteVertexArray=n=>lD(e,(()=>t.deleteVertexArrayOES(n))),this.getVertexArray=()=>lD(e,(()=>e.getParameter(t.VERTEX_ARRAY_BINDING_OES)))}let n="WEBGL_color_buffer_float";const r="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),1===Ye().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=fD(this.gl,e),eM(this.gl,t))this.textureHalfFloatExtension=fD(this.gl,t);else if(Ye().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),eM(this.gl,r))this.colorBufferHalfFloatExtension=fD(this.gl,r);else if(Ye().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",eM(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!eM(this.gl,r))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(r)}this.vertexBuffer=zM(this.gl),this.indexBuffer=PM(this.gl),this.framebuffer=CD(this.gl),this.textureConfig=oD(this.gl,this.textureHalfFloatExtension)}get debug(){return Ye().getBool("DEBUG")}dispose(){if(this.disposed)return;null!=this.program&&aL.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&aL.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;lD(e,(()=>e.finish())),lD(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),lD(e,(()=>e.deleteFramebuffer(this.framebuffer))),lD(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,null))),lD(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null))),lD(e,(()=>e.deleteBuffer(this.indexBuffer))),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),UM(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),GM(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),HM(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),QM(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,r){this.throwIfDisposed(),ZM(this.gl,e,t,n,r,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),YM(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),KM(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(MD(this.gl,this.framebuffer),this.outputTexture=null),lD(this.gl,(()=>this.gl.deleteTexture(e)))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>nL(this.gl,t,n,this.textureConfig)))}downloadPackedMatrixFromBuffer(e,t,n,r,s,a){return rL(this.gl,e,0,0,0,s,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return tL(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const r=eL(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(Ye().getBool("WEBGL_FENCE_API_ENABLED")){const r=e,s=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const e=r.clientWaitSync(s,0,0);return e===r.ALREADY_SIGNALED||e===r.CONDITION_SATISFIED},t=s}else Ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,Ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>sL(this.gl,t,n)))}createProgram(e){this.throwIfDisposed();const t=this.gl;null==this.vertexShader&&(this.vertexShader=LM(t));const n=xD(t);lD(t,(()=>t.attachShader(n,this.vertexShader))),lD(t,(()=>t.attachShader(n,e))),wD(t,n);const r=Object.assign(n,{vao:this.createVertexArray()});return this.debug&&vD(t,r),r}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);const t=this.gl;lD(t,(()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer))),JM(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&(lD(this.gl,(()=>this.gl.deleteProgram(e))),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&vD(this.gl,this.program),lD(this.gl,(()=>this.gl.useProgram(e)))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?RD(this.gl,e,t):OD(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),lD(this.gl,(()=>this.gl.getAttribLocation(e,t)))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),FD(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[r,s]=iD(t,n);this.setOutputMatrixTextureDriver(e,r,s)}setOutputMatrixWriteRegion(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)}setOutputPackedMatrixWriteRegion(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){null!=this.program&&vD(this.gl,this.program),LD(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;if(this.debug){const e=this.getVertexArray();aL.assert(e===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}lD(e,(()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),lD(this.gl,(()=>this.gl.finish()))}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=fD(this.gl,2===Ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(2===Ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(2===Ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2();return void e.endQuery(t.TIME_ELAPSED_EXT)}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await be((()=>this.disposed||this.isQueryAvailable(e,Ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")))),this.getQueryTime(e,Ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(0===t)return null;if(2===t){const t=this.gl;return t.getQueryParameter(e,t.QUERY_RESULT)/1e6}{const t=this.getQueryTimerExtensionWebGL1();return t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(0===t)return!0;if(2===t){const t=this.gl,n=this.getQueryTimerExtensionWebGL2(),r=t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),r&&!this.disjoint}{const t=this.getQueryTimerExtensionWebGL1(),n=t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(t.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise((t=>{this.addItemToPoll((()=>e.isFencePassed()),(()=>t()))}))}pollItems(){const e=function(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}(this.itemsToPoll.map((e=>e.isDoneFn)));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let n;"setTimeoutCustom"in Ye().platform&&(n=Ye().platform.setTimeoutCustom.bind(Ye().platform)),be((()=>(this.pollItems(),0===this.itemsToPoll.length)),(()=>0),null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),DD(this.gl,e,this.framebuffer),this.debug&&LD(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(DD(this.gl,this.outputTexture,this.framebuffer),this.debug&&LD(this.gl)):MD(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const r=this.gl;DD(r,e,this.framebuffer),this.debug&&LD(r),this.outputTexture=e,lD(r,(()=>r.viewport(0,0,t,n))),lD(r,(()=>r.scissor(0,0,t,n)))}setOutputMatrixWriteRegionDriver(e,t,n,r){this.throwIfDisposed(),lD(this.gl,(()=>this.gl.scissor(e,t,n,r)))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(null==this.program)throw new Error("No GPU program is currently set.")}}const{addImpl:oL,bincountImpl:uL,bincountReduceImpl:lL,bitwiseAndImpl:cL,castImpl:hL,ceilImpl:pL,concatImpl:dL,equalImpl:fL,expImpl:mL,expm1Impl:gL,floorImpl:yL,gatherNdImpl:bL,gatherV2Impl:xL,greaterImpl:wL,greaterEqualImpl:vL,lessImpl:kL,lessEqualImpl:IL,linSpaceImpl:NL,logImpl:SL,maxImpl:TL,maximumImpl:CL,minimumImpl:$L,multiplyImpl:EL,negImpl:AL,notEqualImpl:RL,prodImpl:OL,raggedGatherImpl:FL,raggedRangeImpl:_L,raggedTensorToTensorImpl:DL,rangeImpl:ML,rsqrtImpl:LL,scatterImpl:zL,sigmoidImpl:PL,simpleAbsImpl:BL,sliceImpl:WL,sparseFillEmptyRowsImpl:UL,sparseReshapeImpl:VL,sparseSegmentReductionImpl:GL,sqrtImpl:jL,staticRegexReplaceImpl:HL,stridedSliceImpl:qL,stringNGramsImpl:KL,stringSplitImpl:XL,stringToHashBucketFastImpl:YL,subImpl:JL,tileImpl:ZL,topKImpl:QL,transposeImpl:ez,uniqueImpl:tz}=H;function nz(e,t){return["x","y","z","w","u","v"].slice(0,t).map((t=>`${e}.${t}`))}function rz(e,t){return 1===t?[e]:nz(e,t)}class sz{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=EM(this.outputShape.length),0===this.rank)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{const e=rz("rc",this.rank),t=IM(this.rank),n=this.getOutOfBoundsCondition(e),r=this.getSetup(e),s=this.getOutput(e);this.userCode=`\n void main() {\n ${t} rc = getOutputCoords();\n\n if(${n}) {\n setOutput(vec4(0));\n } else {\n ${r}\n\n setOutput(vec4(${s}));\n }\n }\n `}}getSourceCoordsArr(e){const t=[];for(let n=0;n<=1;n++)for(let r=0;r<=1;r++){let s=`${0===n?"r":"rp1"}, ${0===r?"c":"cp1"}`;for(let t=2;t<this.rank;t++)s=`${e[e.length-1-t]},`+s;t.push(s)}return t}getOutOfBoundsCondition(e){if(1===this.rank)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let n=this.rank-2;n<this.rank;n++)t+=`${e[n]} >= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n<this.rank-1&&(t+="||");return t}getSetup(e){if(1===this.rank)return"";const t=e.slice(-2),n=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],r=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`\n int r = ${t[0]};\n int c = ${t[1]};\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= ${n};\n bool rEdge = rp1 >= ${r};\n `}getOutput(e){const t=this.getSourceCoordsArr(e);return 1===this.rank?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}),\n cEdge ? 0. : getA(${t[1]}),\n rEdge ? 0. : getA(${t[2]}),\n rEdge || cEdge ? 0. : getA(${t[3]})`}}class az{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=EM(this.outputShape.length);let n="";for(let e=0;e<4;e++){let t="thisRC = rc;";e%2==1&&(t+="thisRC.z += 1;"),e>1&&(t+="thisRC.y += 1;"),n+=`\n ${t}\n ${e>0?"if(thisRC.y < rows && thisRC.z < cols){":""}\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${e}] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n ${e>0?"}":""}\n `}var r,s;this.userCode=`\n ${r=t,s=this.enableShapeUniforms,`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${s?function(e,t,n="index"){const r=function(e,t){const n=e.length,r=e.map((e=>`${t}[${e}]`)),s=new Array(n-1);s[n-2]=r[n-1];for(let e=n-3;e>=0;--e)s[e]=`(${s[e+1]} * ${r[e+1]})`;return s}(e.map(((e,t)=>t)),t);return r.map(((t,s)=>`int ${e[s]} = ${n} / ${r[s]}; ${s===r.length-1?`int ${e[s+1]} = ${n} - ${e[s]} * ${r[s]}`:`index -= ${e[s]} * ${r[s]}`};`)).join("")}(["r","c","d"],"inputShape"):lM(["r","c","d"],r)}\n return ivec3(r, c, d);\n }\n `}\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":hM(e)}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};\n int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};\n\n ${n}\n\n setOutput(result);\n }\n `}}var iz=n(96763);class oz{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(e,t,n){const r=lz(t,n),s=cz(e,r,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);const a=uz(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();const e=this.freeTextures[s].pop();return this.usedTextures[s].push(e),e}let i;return r===rD.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===rD.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===rD.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===rD.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===rD.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[s].push(i),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),i}releaseTexture(e,t,n,r){if(null==this.freeTextures)return;const s=lz(n,r),a=cz(t,s,r);a in this.freeTextures||(this.freeTextures[a]=[]);const i=uz(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,r),o=Ye().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");-1!==o&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;const u=this.usedTextures[a],l=u&&u.indexOf(e);if(null==l||l<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u[l]=u[u.length-1],u.pop(),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;iz.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;iz.log(`Bytes allocated: ${this._numBytesAllocated}`),iz.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(null!=this.freeTextures){for(const e in this.freeTextures)this.freeTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e.texture)}));for(const e in this.usedTextures)this.usedTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e.texture)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}}function uz(e,t,n,r,s){const a=function(e,t){switch(e){case rD.PACKED_2X2_FLOAT32:return qM(t);case rD.PACKED_2X2_FLOAT16:return XM(t);case rD.UNPACKED_FLOAT32:return WM(t);case rD.UNPACKED_FLOAT16:return VM(t);case rD.PACKED_4X1_UNSIGNED_BYTE:return jM(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,r);let i;if(s){const[t,n]=iD(e[0],e[1]);i=t*n}else{const[t,n]=sD(e[0],e[1]);i=t*n}const o=function(e,t){const n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}(n,a);return i*o}function lz(e,t){if(e===nD.UPLOAD)return rD.PACKED_2X2_FLOAT32;if(e===nD.RENDER||null==e)return function(e){return Ye().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?rD.PACKED_2X2_FLOAT32:rD.UNPACKED_FLOAT32:e?rD.PACKED_2X2_FLOAT16:rD.UNPACKED_FLOAT16}(t);if(e===nD.DOWNLOAD||e===nD.PIXELS)return rD.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function cz(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class hz{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=EM(this.outputShape.length),this.userCode=`\n float unaryOperation(float x) {\n ${t}\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}const pz="if (isnan(x)) return x;",dz="return x;",fz="return abs(x);",mz="return (x >= 0.0) ? x : (exp(x) - 1.0);",gz=pz+"\n return (x < 0.0) ? 0.0 : x;\n",yz=pz+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",bz="return x;",xz="return 1.0 / (1.0 + exp(-1.0 * x));",wz="return x;",vz="\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n",kz="\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",Iz="\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",Nz="return 1.0 / (1.0 + exp(-1.0 * x));";class Sz{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=EM(this.outputShape.length),this.userCode=`\n vec4 unaryOperation(vec4 x) {\n ${t}\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}class Tz{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=EM(this.outputShape.length);const t=e.length,n=rz("rc",t),r=IM(t),s=function(e,t){if(1===e)return"rc";let n="";for(let r=0;r<e;r++)n+=t[r],r<e-1&&(n+=",");return n}(t,n),a=n.slice(-2),i=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=`\n void main() {\n ${r} rc = getOutputCoords();\n vec4 packedInput = getA(${s});\n\n setOutput(getChannel(packedInput, ${i}));\n }\n `}}var Cz=n(96763);const $z=_d,Ez={},Az=Ye().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");class Rz extends Y{nextDataId(){return Rz.nextDataId++}constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!Ye().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(null!=e){if(e instanceof iL)t=e;else{const n=eD(Ye().getNumber("WEBGL_VERSION"),e);t=new iL(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const e=eD(Ye().getNumber("WEBGL_VERSION"));t=new iL(e),this.binaryCache=((n=Ye().getNumber("WEBGL_VERSION"))in Ez||(Ez[n]={}),Ez[n]),this.gpgpuCreatedLocally=!0}var n;this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new oz(this.gpgpu),this.numMBBeforeWarning=null==Ye().global.screen?1024:Ye().global.screen.height*Ye().global.screen.width*window.devicePixelRatio*600/1024/1024,this.texData=new X(this,yi())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,n,r,s,a){const i=this.makeTensorInfo(t,n),o=this.texData.get(i.dataId);o.isPacked=!1,o.texture={texture:e,texShape:[r,s]},o.texShape=[r,s];const u=VD(t),l=new DM(u,!1,a),c=this.runWebGLProgram(l,[i],n,[[r,s]]);return c.shape=t,o.texture=null,this.disposeIntermediateTensorInfo(i),c.dataId}write(e,t,n){if((Ye().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||Ye().getBool("DEBUG"))&&this.checkNumericalProblems(e),"complex64"===n&&null!=e)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const r={id:this.nextDataId()};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:nD.UPLOAD,refCount:1}),r}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){this.texData.get(e).refCount++}decRef(e){this.texData.has(e)&&this.texData.get(e).refCount--}move(e,t,n,r,s){if(Ye().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===r)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:r,values:t,usage:nD.UPLOAD,refCount:s})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){const t=this.texData.get(e),{values:n,dtype:r,complexTensorInfos:s,slice:a,shape:i,isPacked:o}=t;if(null!=a){let t;t=o?new Sz(i,bz):new hz(i,bz);const n=this.runWebGLProgram(t,[{dataId:e,shape:i,dtype:r}],r),s=this.readSync(n.dataId);return this.disposeIntermediateTensorInfo(n),s}if(null!=n)return this.convertAndCacheOnCPU(e);if("string"===r)return n;const u=null!=this.activeTimers;let l,c;return u&&(l=Zs()),c="complex64"===r?Em(this.readSync(s.real.dataId),this.readSync(s.imag.dataId)):this.getValuesFromTexture(e),u&&(this.downloadWaitMs+=Zs()-l),this.convertAndCacheOnCPU(e,c)}async read(e){if(this.pendingRead.has(e)){const t=this.pendingRead.get(e);return new Promise((e=>t.push(e)))}const t=this.texData.get(e),{values:n,shape:r,slice:s,dtype:a,complexTensorInfos:i,isPacked:o}=t;if(null!=s){let t;t=o?new Sz(r,bz):new hz(r,bz);const n=this.runWebGLProgram(t,[{dataId:e,shape:r,dtype:a}],a),s=this.read(n.dataId);return this.disposeIntermediateTensorInfo(n),s}if(null!=n)return this.convertAndCacheOnCPU(e);if(Ye().getBool("DEBUG")&&!Ye().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===Ye().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u,l,c=null;if("complex64"!==a&&Ye().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);const t=this.texData.get(u.dataId);c=this.gpgpu.createBufferFromTexture(t.texture.texture,...aD(r))}if(this.pendingRead.set(e,[]),"complex64"!==a&&await this.gpgpu.createAndWaitForFence(),"complex64"===a){const e=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]);l=Em(e[0],e[1])}else if(null==c)l=this.getValuesFromTexture(e);else{const e=le(r);l=this.gpgpu.downloadFloat32MatrixFromBuffer(c,e)}if(null!=u&&this.disposeIntermediateTensorInfo(u),null!=c){const e=this.gpgpu.gl;lD(e,(()=>e.deleteBuffer(c)))}const h=this.convertAndCacheOnCPU(e,l),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach((e=>e(h))),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&yi().removeDataId(e,this),this.pendingDeletes--),h}readToGPU(e,t={}){const n=this.texData.get(e),{values:r,shape:s,slice:a,dtype:i,isPacked:o,texture:u}=n;if("complex64"===i)throw new Error("Does not support reading texture for complex64 dtype.");if(null!=a){let n;n=o?new Sz(s,bz):new hz(s,bz);const r=this.runWebGLProgram(n,[{dataId:e,shape:s,dtype:i}],i),a=this.readToGPU(r,t);return this.disposeIntermediateTensorInfo(r),a}if(null==u)throw null!=r?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const l=this.decode(e,t.customTexShape),c=yi().makeTensorFromTensorInfo(l),h=this.texData.get(l.dataId);return Object.assign({tensorRef:c},h.texture)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>ta(e)));return Mo(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Mo(e.shape,e.dtype,t)}checkNumericalProblems(e){if(null!=e)for(let t=0;t<e.length;t++){const n=e[t];if(!pD(n)){if(Ye().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`);throw Error(`The value ${n} cannot be represented on this device.`)}}}getValuesFromTexture(e){const{shape:t,dtype:n,isPacked:r}=this.texData.get(e),s=le(t);if(Ye().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const n=this.decode(e),r=this.texData.get(n.dataId),a=this.gpgpu.downloadMatrixFromPackedTexture(r.texture.texture,...aD(t)).subarray(0,s);return this.disposeIntermediateTensorInfo(n),a}const a=Ye().getBool("WEBGL_PACK")&&!0===r,i=a?VD(t):t,o=a?new FM(i):new OM(i),u=this.runWebGLProgram(o,[{shape:i,dtype:n,dataId:e}],"float32"),l=this.texData.get(u.dataId),c=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(l.texture.texture,l.texShape[0],l.texShape[1]).subarray(0,s);return this.disposeIntermediateTensorInfo(u),c}timerAvailable(){return Ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){const t=this.activeTimers,n=[];let r=!1;null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e();const s=ra(this.activeTimers.map((e=>e.query))).filter((e=>null!=e)),a=ra(this.activeTimers.map((e=>e.name))).filter((e=>null!=e));this.activeTimers=t,r&&(this.programTimersStack=null);const i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(Ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(s);i.kernelMs=re(e),i.getExtraProfileInfo=()=>e.map(((e,t)=>({name:a[t],ms:e}))).map((e=>`${e.name}: ${e.ms}`)).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return Ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Zs(),endMs:null}}endTimer(e){return Ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Zs(),e)}async getQueryTime(e){if(Ye().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);const{complexTensorInfos:n}=this.texData.get(e);return null!=n&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:t,dtype:n,texShape:r,usage:s,isPacked:a,slice:i}=this.texData.get(e),o=i&&i.origDataId||e,u=this.dataRefCount.get(o);u>1?this.dataRefCount.set(o,u-1):(this.dataRefCount.delete(o),null!=t&&(this.numBytesInGPU-=this.computeBytes(r,n),this.textureManager.releaseTexture(t,r,s,a)));const l=this.texData.get(e);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=Az){return Ye().getBool("WEBGL_CPU_FORWARD")&&e.every((e=>null==this.texData.get(e.dataId).texture&&le(e.shape)<t))}getGPGPUContext(){return this.gpgpu}where(e){ks("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return $z(e.shape,t)}packedUnaryOp(e,t,n){const r=new Sz(e.shape,t),s=this.compileAndRun(r,[e],n);return yi().makeTensorFromTensorInfo(s)}abs(e){if(this.shouldExecuteOnCPU([e])&&"complex64"!==e.dtype){const t=BL(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,t)}if(Ye().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,fz,e.dtype);const t=new hz(e.shape,fz),n=this.compileAndRun(t,[e]);return yi().makeTensorFromTensorInfo(n)}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&Ee(n[0])){const s=n.map((e=>ea(e)));r=this.write(s,e,t)}else r=this.write(n,e,t);return this.texData.get(r).usage=null,{dataId:r,shape:e,dtype:t}}makeOutput(e,t,n){return yi().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){const t=new Tz(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new sz(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[WD(e.shape),...UD(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},s=[WD(t),...UD(t)],a=new az(s,n),i=[n],o=this.runWebGLProgram(a,[r],e.dtype,i,!0);return{dataId:o.dataId,shape:t,dtype:o.dtype}}decode(e,t){const n=this.texData.get(e),{isPacked:r,shape:s,dtype:a}=n;null!=t&&ie(le(s)<=t[0]*t[1]*4,(()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data."));const i=VD(s);let o;o=r?new RM(i):new AM(i);const u=[null!=t?t:aD(i)];return{dtype:a,shape:s,dataId:this.runWebGLProgram(o,[{shape:i,dtype:a,dataId:e}],a,u,!0,t).dataId}}runWebGLProgram(e,t,n,r,s=!1,a){const i=this.makeTensorInfo(e.outputShape,n),o=this.texData.get(i.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===tD.DENSE){const t=null!=a?a:aD(e.outputShape);o.texShape=t.map((e=>2*e))}if(null!=e.outTexUsage&&(o.usage=e.outTexUsage),0===le(i.shape))return o.values=ke(i.dtype,0),i;const u=[],l=t.map((t=>{if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let n=this.texData.get(t.dataId);if(null==n.texture){if(!e.packedInputs&&le(t.shape)<=Ye().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:n.values};e.packedInputs&&(n.isPacked=!0,n.shape=t.shape)}if(this.uploadToGPU(t.dataId),!!n.isPacked!=!!e.packedInputs)t=n.isPacked?this.unpackTensor(t):this.packTensor(t),u.push(t),n=this.texData.get(t.dataId);else if(n.isPacked&&!HD(n.shape,t.shape)){const e=t,r=t.shape;t.shape=n.shape,t=this.packedReshape(t,r),u.push(t),n=this.texData.get(t.dataId),e.shape=r}return{shape:t.shape,texData:n,isUniform:!1}}));this.uploadToGPU(i.dataId);const c={shape:i.shape,texData:o,isUniform:!1},h=function(e,t,n){let r="";t.concat(n).forEach((t=>{const s=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!t.isUniform){const a=t.texData.texShape,{useSqueezeShape:i,uniformShape:o,keptDims:u}=NM(e.packedInputs,t.shape,a);let l="",c="",h="";if(1===o.length&&e.packedInputs){const e=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];l=`${e[0]>1}_${e[1]>1}`}else if(2!==o.length||e.packedInputs){if(o.length>2&&!e.packedInputs){const e=De(o);h=`${e[0]===a[1]}_${e[e.length-1]===a[1]}`}}else c=`${o[0]>1}_${o[1]>1}`;const p=t.shape.length,d=2===o.length&&pe(t.shape,a),f=1===le(t.shape),m=gu(t.shape,n.shape),g=!e.packedInputs&&p===n.shape.length&&pe(a,n.texData.texShape),y=e.packedInputs||o.length>2?"":`${a[0]>1}_${a[1]>1}`;r+=`${p}_${g}_${i?u:""}_${o.length}_${f}_${m}_${d}_${l}_${c}_${h}_${y}_${s}`}else{const e=t.isUniform?"uniform":t.texData.texShape;r+=`${t.shape}_${e}_${s}`}}));const s=e.userCode;let a=e.constructor.name;return a+="_"+r+"_"+s+`${Ye().getNumber("WEBGL_VERSION")}`,a}(e,l,c),p=this.getAndSaveBinary(h,(()=>function(e,t,n,r){const s=n.map(((e,n)=>{const r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0&&(r.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:r}})),a=s.map((e=>e.shapeInfo)),i={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},o=fM(s,i,t),u=gD(e.gl,o),l=e.createProgram(u);return Ye().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:u,source:o,webGLProgram:l,inShapeInfos:a,outShapeInfo:i,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(e.buildVao(l),Object.assign({program:t,fragmentShader:u,source:o,webGLProgram:l,inShapeInfos:a,outShapeInfo:i},CM(e,t,l)))}(this.gpgpu,e,l,c))),d=null!=this.activeTimers;let f;d&&(f=this.startTimer()),Ye().get("ENGINE_COMPILE_ONLY")||function(e,t,n,r,s){t.program.enableShapeUniforms||($M(t.inShapeInfos,n),$M([t.outShapeInfo],[r]));const a=r.texData.texture,i=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(a.texture,i[0],i[1]):e.setOutputMatrixTexture(a.texture,i[0],i[1]),e.setProgram(t.webGLProgram),e.bindVertexArray(t.webGLProgram.vao),1===Ye().getNumber("WEBGL_VERSION")&&null!==t.infLoc&&e.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&e.gl.uniform1f(t.nanLoc,NaN);for(let r=0;r<n.length;++r){const s=n[r],{uniform:a,offset:i,shape:o,texShape:u}=t.variablesLocations[r];if(o){const{uniformShape:n}=NM(t.program.packedInputs,s.shape,s.texData.texShape);switch(n.length){case 1:e.gl.uniform1iv(o,new Int32Array(n));break;case 2:e.gl.uniform2iv(o,new Int32Array(n));break;case 3:e.gl.uniform3iv(o,new Int32Array(n));break;case 4:e.gl.uniform4iv(o,new Int32Array(n))}}if(u&&e.gl.uniform2i(u,s.texData.texShape[0],s.texData.texShape[1]),null!=a)if(s.isUniform)if(le(s.shape)<2)e.gl.uniform1f(a,s.uniformValues[0]);else{let t=s.uniformValues;t instanceof Float32Array||(t=new Float32Array(t)),e.gl.uniform1fv(a,t)}else null!=s.texData.slice&&null!=i&&e.gl.uniform1i(i,s.texData.slice.flatOffset),e.setInputMatrixTexture(s.texData.texture.texture,a,r)}const o=t.outShapeLocation;if(o)switch(r.shape.length){case 1:e.gl.uniform1iv(o,new Int32Array(r.shape));break;case 2:e.gl.uniform2iv(o,new Int32Array(r.shape));break;case 3:e.gl.uniform3iv(o,new Int32Array(r.shape));break;case 4:e.gl.uniform4iv(o,new Int32Array(r.shape))}if(t.outShapeStridesLocation){const n=De(r.shape);switch(r.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(n));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(n));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(n))}}if(t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,r.texData.texShape[0],r.texData.texShape[1]),t.program.customUniforms&&s)for(let n=0;n<t.program.customUniforms.length;++n){const r=t.program.customUniforms[n],a=t.customUniformLocations[n],i=s[n];if("float"===r.type)e.gl.uniform1fv(a,i);else if("vec2"===r.type)e.gl.uniform2fv(a,i);else if("vec3"===r.type)e.gl.uniform3fv(a,i);else if("vec4"===r.type)e.gl.uniform4fv(a,i);else if("int"===r.type)e.gl.uniform1iv(a,i);else if("ivec2"===r.type)e.gl.uniform2iv(a,i);else if("ivec3"===r.type)e.gl.uniform3iv(a,i);else{if("ivec4"!==r.type)throw Error(`uniform type ${r.type} is not supported yet.`);e.gl.uniform4iv(a,i)}}e.executeProgram()}(this.gpgpu,p,l,c,r),u.forEach((e=>this.disposeIntermediateTensorInfo(e))),d&&(f=this.endTimer(f),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(f)}));const m=Ye().getNumber("WEBGL_FLUSH_THRESHOLD");if(m>0){const e=Zs();e-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!Ye().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&!1===s){const e=this.unpackTensor(i);return this.disposeIntermediateTensorInfo(i),e}return i}compileAndRun(e,t,n,r,s=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,r,s)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(Ye().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach((e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]})),this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return null==this.floatPrecisionValue&&(this.floatPrecisionValue=wi((()=>{if(!Ye().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=Ye().getBool("DEBUG");Ye().set("DEBUG",!1);const t=this.abs(tu(1e-8)).dataSync()[0];if(Ye().set("DEBUG",e),t>0)return 32}return 16}))),this.floatPrecisionValue}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}uploadToGPU(e){const t=this.texData.get(e),{shape:n,dtype:r,values:s,texture:a,usage:i,isPacked:o}=t;if(null!=a)return;const u=null!=this.activeTimers;let l;u&&(l=Zs());let c=t.texShape;if(null==c&&(c=GD(n,o),t.texShape=c),null!=s){const e=VD(n);let a,i=c[1],h=c[0];const p=s instanceof Uint8Array||s instanceof Uint8ClampedArray;!o&&p||([i,h]=iD(c[0],c[1])),a=o?new MM(e,p):new DM(e,p);const d=p?[h,i]:c,f=this.makeTensorInfo(d,r),m=this.texData.get(f.dataId);m.usage=p?nD.PIXELS:nD.UPLOAD,m.texShape=d,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(f.dataId),i,h,s);const g=[[h,i]],y=!0,b=this.runWebGLProgram(a,[f],r,g,y),x=this.texData.get(b.dataId);t.texShape=x.texShape,t.isPacked=x.isPacked,t.usage=x.usage,Ye().get("ENGINE_COMPILE_ONLY")?this.disposeData(b.dataId):(t.texture=x.texture,t.values=null,this.texData.delete(b.dataId)),this.disposeIntermediateTensorInfo(f),u&&(this.uploadWaitMs+=Zs()-l)}else{const e=this.acquireTexture(c,i,r,o);t.texture=e}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:r}=n;return null!=t&&(n.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){const n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length);for(let t=0;t<n.length;++t)n[t]=Math.round(e[t]);return n}throw new Error(`Unknown dtype ${t}`)}(t,r)),n.values}acquireTexture(e,t,n,r){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){const e=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,Cz.warn(`High memory usage in GPU: ${e} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,r)}computeBytes(e,t){return e[0]*e[1]*Ce(t)}checkCompileCompletion(){for(const[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){const e=[];if(this.gpgpu.parallelCompilationExtension){for(const[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}for(const[,t]of Object.entries(this.binaryCache)){const n=new Promise((e=>{try{this.checkCompletion_(t),e(!0)}catch(e){throw e}}));e.push(n)}return Promise.all(e)}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await am(),this.checkCompletionAsync_(e))}checkCompletion_(e){if(!1===this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)){if(Cz.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),!1===this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS))throw bD(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.");throw new Error("Failed to link vertex and fragment shaders.")}return!0}getUniformLocations(){for(const e of Object.values(this.binaryCache)){this.gpgpu.buildVao(e.webGLProgram);const{variablesLocations:t,customUniformLocations:n,infLoc:r,nanLoc:s,outShapeLocation:a,outShapeStridesLocation:i,outTexShapeLocation:o}=CM(this.gpgpu,e.program,e.webGLProgram);e.variablesLocations=t,e.customUniformLocations=n,e.infLoc=r,e.nanLoc=s,e.outShapeLocation=a,e.outShapeStridesLocation=i,e.outTexShapeLocation=o}}createTensorFromGPUData(e,t,n){e.channels=e.channels||"RGBA";const{texture:r,height:s,width:a,channels:i}=e,o=yi().backend;if(!o.gpgpu.gl.isTexture(r))throw new Error("The texture is invalid. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through 'new tf.MathBackendWebGL(customCanvas)'.");const u=o.writeTexture(r,t,n,s,a,i);return yi().makeTensorFromDataId(u,t,n,o)}}Rz.nextDataId=0;const Oz="4.20.0";function Fz(){Ye().set("WEBGL_FORCE_F16_TEXTURES",!0)}Ka()&&Ai("webgl",(()=>new Rz),2);const _z={forceHalfFloat:Fz},Dz="\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n";class Mz{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=bu(t,n),this.enableShapeUniforms=EM(this.outputShape.length),this.userCode=`\n float binaryOperation(float a, float b) {\n ${e}\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n `}}const Lz="\n result.r = isNaN.r ? NAN : result.r;\n result.g = isNaN.g ? NAN : result.g;\n result.b = isNaN.b ? NAN : result.b;\n result.a = isNaN.a ? NAN : result.a;\n";class zz{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=bu(t,n);const s=this.outputShape.length;this.enableShapeUniforms=EM(s);let a="";if(r)if(0===s||1===le(this.outputShape))a="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(a=`\n ${IM(s)} coords = getOutputCoords();\n `,1===s)this.enableShapeUniforms?a+="\n result.y = (coords + 1) >= outShape ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ":a+=`\n result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n `;else{const e=rz("coords",s);this.enableShapeUniforms?a+=`\n bool nextRowOutOfBounds =\n (${e[s-2]} + 1) >= outShape[${s} - 2];\n bool nextColOutOfBounds =\n (${e[s-1]} + 1) >= outShape[${s} - 1];\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `:a+=`\n bool nextRowOutOfBounds =\n (${e[s-2]} + 1) >= ${this.outputShape[s-2]};\n bool nextColOutOfBounds =\n (${e[s-1]} + 1) >= ${this.outputShape[s-1]};\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `}this.userCode=`\n vec4 binaryOperation(vec4 a, vec4 b) {\n ${e}\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n ${a}\n\n setOutput(result);\n }\n `}}function Pz(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const Bz={kernelName:xn,backendName:"webgl",kernelFunc:Pz};function Wz(e){const{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.makeTensorInfo(r.shape,"complex64"),i=n.texData.get(a.dataId),o=Pz({inputs:{x:r},backend:n}),u=Pz({inputs:{x:s},backend:n});return i.complexTensorInfos={real:o,imag:u},a}const Uz={kernelName:Et,backendName:"webgl",kernelFunc:Wz},Vz="return (a < 0.) ? b * a : a;",Gz="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",jz={kernelName:Sn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r,i=n.makeTensorInfo([],"float32",Ys(a,"float32")),o=Ye().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new zz(Gz,s.shape,i.shape):new Mz(Vz,s.shape,i.shape),u=n.runWebGLProgram(o,[s,i],"float32");return n.disposeIntermediateTensorInfo(i),u}},Hz="return (a < 0.) ? b * a : a;",qz="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",Kz={kernelName:hr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r,alpha:s}=t,a=Ye().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new zz(qz,r.shape,s.shape):new Mz(Hz,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],"float32")}},Xz="if (isnan(x)) return x;";function Yz({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:s,backend:a})=>{const{x:i}=s,o=a,u=r||i.dtype;if(o.shouldExecuteOnCPU([i])&&null!=n){const e=o.texData.get(i.dataId),t=n(e.values,u);return o.makeTensorInfo(i.shape,u,t)}let l;return l=Ye().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new Sz(i.shape,t):new hz(i.shape,e),o.runWebGLProgram(l,[i],u)}}function Jz({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:s,dtype:a}){return({inputs:i,backend:o})=>{const{a:u,b:l}=i,c=o;if(r&&"complex64"===u.dtype){const t=c.texData.get(u.dataId),n=c.texData.get(l.dataId),[r,s]=[[t.complexTensorInfos.real,n.complexTensorInfos.real],[t.complexTensorInfos.imag,n.complexTensorInfos.imag]].map((t=>{const[n,r]=t,s={dataId:n.dataId,dtype:n.dtype,shape:u.shape},a={dataId:r.dataId,dtype:r.dtype,shape:l.shape},i=new Mz(e,u.shape,l.shape);return c.runWebGLProgram(i,[s,a],Ea(n.dtype,r.dtype))})),a=Wz({inputs:{real:r,imag:s},backend:c});return c.disposeIntermediateTensorInfo(r),c.disposeIntermediateTensorInfo(s),a}const h=a||Ea(u.dtype,l.dtype);if(("string"===u.dtype||"string"===l.dtype||c.shouldExecuteOnCPU([u,l]))&&null!=s){const e=c.texData.get(u.dataId).values,t=c.texData.get(l.dataId).values,n="string"===u.dtype?lg(e):e,r="string"===u.dtype?lg(t):t,[a,i]=s(u.shape,l.shape,n,r,h),o=c.makeTensorInfo(i,h);return c.texData.get(o.dataId).values=a,o}let p;return p=Ye().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new zz(t,u.shape,l.shape,n):new Mz(e,u.shape,l.shape),c.runWebGLProgram(p,[u,l],h)}}function Zz(e,t=!1){if("linear"===e)return t?wz:dz;if("relu"===e)return t?kz:gz;if("elu"===e)return t?vz:mz;if("relu6"===e)return t?Iz:yz;if("prelu"===e)return t?qz:Hz;if("leakyrelu"===e)return t?Gz:Vz;if("sigmoid"===e)return t?Nz:xz;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}class Qz{constructor(e,t,n,r=!1,s=!1,a=!1,i=null,o=!1,u=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=EM(this.outputShape.length);const l=r?e[1]:e[2],c=Math.ceil(l/2),h=r?"i * 2, rc.y":"rc.y, i * 2",p=s?"rc.z, i * 2":"i * 2, rc.z",d=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let m="",g="";i&&(m=o?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${i}\n }`:u?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${i}\n }`:`vec4 activation(vec4 x) {\n ${i}\n }`,g="result = activation(result);");const y=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),u&&this.variableNames.push("leakyreluAlpha");let b="rc.x",x="rc.x";e[0]<t[0]?b=`imod(rc.x, ${e[0]})`:t[0]<e[0]&&(x=`imod(rc.x, ${t[0]})`),this.userCode=`\n ${m}\n // Don't use uniform for sharedDimensionPacked for performance.\n const float sharedDimension = ${c}.0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n int batchA = ${b};\n int batchB = ${x};\n for (int i = 0; i < ${c}; i++) {\n vec4 a = getMatrixA(batchA, ${h});\n vec4 b = getMatrixB(batchB, ${p});\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += (${d[0]} * ${f[0]});\n result += (${d[1]} * ${f[1]});\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n ${y}\n\n ${g}\n\n setOutput(result);\n }\n `}}const eP={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class tP{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=bu(t,n),this.userCode=`\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n ${e}\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n `}}const nP="return a * b;";function rP(e){const{inputs:t,backend:n}=e,{a:r,b:s}=t,a=Ea(r.dtype,s.dtype);if("complex64"===r.dtype){const e=n.texData.get(r.dataId),t=n.texData.get(s.dataId),a=new tP(eP.REAL,r.shape,s.shape),i=new tP(eP.IMAG,r.shape,s.shape),o=[{dataId:e.complexTensorInfos.real.dataId,dtype:e.complexTensorInfos.real.dtype,shape:r.shape},{dataId:e.complexTensorInfos.imag.dataId,dtype:e.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:t.complexTensorInfos.real.dataId,dtype:t.complexTensorInfos.real.dtype,shape:s.shape},{dataId:t.complexTensorInfos.imag.dataId,dtype:t.complexTensorInfos.imag.dtype,shape:s.shape}],u=n.runWebGLProgram(a,o,"float32"),l=n.runWebGLProgram(i,o,"float32"),c=Wz({inputs:{real:u,imag:l},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(l),c}if(n.shouldExecuteOnCPU([r,s])){const e=n.texData.get(r.dataId),t=n.texData.get(s.dataId),[i,o]=EL(r.shape,s.shape,e.values,t.values,a),u=n.makeTensorInfo(o,a);return n.texData.get(u.dataId).values=i,u}let i;return i=Ye().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new zz(nP,r.shape,s.shape):new Mz(nP,r.shape,s.shape),n.runWebGLProgram(i,[r,s],a)}const sP={kernelName:Qn,backendName:"webgl",kernelFunc:rP};function aP(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{shape:a}=r,i=n,o=le(s.shape),u=xe(a,o),l=le(u);ie(o===l,(()=>`The new shape (${u}) has ${l} elements and the old shape (${s.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`));const c=i.texData.get(s.dataId);return!c.isPacked||HD(s.shape,u)||null!==c.texture&&HD(c.shape,u)?(i.incRef(s.dataId),{dataId:s.dataId,shape:u,dtype:s.dtype}):function(e,t,n){const r=[WD(e.shape),...UD(e.shape)],s={dtype:e.dtype,shape:r,dataId:e.dataId},a=[WD(t),...UD(t)],i=new az(a,r),o=[r],u=n.runWebGLProgram(i,[s],e.dtype,o,!0);return{dataId:u.dataId,shape:t,dtype:u.dtype}}(s,u,i)}const iP={kernelName:wr,backendName:"webgl",kernelFunc:aP};class oP{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];const i=4*Math.floor(n/4),o=n%4;let u="sumValue += dot(values, ones);";if(null!=t){const e=1/t;u=`sumValue += dot(values * ${de(e)?e.toPrecision(2):e}, ones);`}let l="";s%n>0&&(l=`\n if (inIdx < 0 || inIdx >= ${s}) {\n return 0.0;\n }\n `),this.userCode=`\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${l}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${n};\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${i}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${u}\n }\n\n int inIdx = inOffset + ${i};\n if (${1===o}) {\n vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n ${u}\n } else if (${2===o}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1), 0.0, 0.0);\n\n ${u}\n } else if (${3===o}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2), 0.0);\n\n ${u}\n }\n setOutput(sumValue);\n }\n `}}class uP{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let i="0.0",o="";"prod"===t?i="1.0":"min"===t?(i="1.0 / 1e-20",o="min"):"max"===t&&(i="-1.0 / 1e-20",o="max");let u=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"sum"===t?u="sumValue":"prod"===t?u="prodValue":"all"===t?u="allValue":"any"===t&&(u="anyValue");const l=4*Math.floor(n/4),c=n%4;let h=`\n if (${"sum"===t}) {\n sumValue += dot(values, ones);\n } else if (${"prod"===t}) {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = ${o}(values, minMaxValue);\n if (${"min"===t} || ${"max"===t}) {\n minMaxValue = ${o}(values, minMaxValue);\n bvec4 isNaN = isnan(values);\n if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {\n minMaxValue = vec4(NAN);\n }\n }\n }\n `,p="vec4";"all"===t?(i="1.0",h="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===t&&(i="0.0",h="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",p="bvec4");let d="";s%n>0&&(d=`\n if (inIdx < 0 || inIdx >= ${s}) {\n return initializationValue;\n }\n `),this.userCode=`\n const float initializationValue = ${i};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${d}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${n};\n\n vec4 minMaxValue = vec4(${i});\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < ${l}; i += 4) {\n int inIdx = inOffset + i;\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${h}\n }\n\n int inIdx = inOffset + ${l};\n if (${1===c}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${h}\n } else if (${2===c}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n ${h}\n } else if (${3===c}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n ${h}\n }\n setOutput(${u});\n }\n `}}function lP(e,t,n,r){const s=function(e){const t=[];for(;0===t.length||1!==t[t.length-1].outSize;){const n=t.length?t[t.length-1].outSize:e[1],r=fm(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}(e.shape);let a=e;for(let i=0;i<s.length;i++){const{inSize:o,windowSize:u,outSize:l}=s[i];let c,h;c="mean"===n?0===i?new oP({windowSize:u,inSize:o,batchSize:e.shape[0],outSize:l},o):new oP({windowSize:u,inSize:o,batchSize:e.shape[0],outSize:l}):new uP({windowSize:u,inSize:o,batchSize:e.shape[0],outSize:l},n),h=a,a=r.runWebGLProgram(c,[a],t),h.dataId!==e.dataId&&r.disposeIntermediateTensorInfo(h)}return a}class cP{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];this.outputShape=n,this.rank=n.length;const r=IM(this.rank),s=function(e){const t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t);for(let t=0;t<e.length;t++)r[e[t]]=n[t];return r.join()}(t);this.userCode=`\n void main() {\n ${r} resRC = getOutputCoords();\n setOutput(getA(${s}));\n }\n `}}class hP{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const r=IM(this.rank),s=nz("rc",this.rank),a=new Array(this.rank);for(let e=0;e<t.length;e++)a[t[e]]=s[e];const i=`vec2(${a.slice(-2).join()})`,o=`++${s[this.rank-1]} < ${n[this.rank-1]}`,u=`getChannel(getA(${a.join()}), ${i})`;this.userCode=`\n void main() {\n ${r} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result[0] = ${u};\n if(${o}) {\n result[1] = ${u};\n }\n --${s[this.rank-1]};\n if(++${s[this.rank-2]} < ${n[this.rank-2]}) {\n result[2] = ${u};\n if(${o}) {\n result[3] = ${u};\n }\n }\n setOutput(result);\n }\n `}}function pP(e,t,n){const r=Ye().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new hP(e.shape,t):new cP(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function dP(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r;return function(e,t,n,r){const s=t,a=e.shape.length,i=we(s,e.shape);let o=i;const u=xh(o,a),l=null!=u;let c=e;l&&(c=pP(e,u,r),o=vh(o.length,a)),bh("sum",o,a);const[h,p]=gh(c.shape,o);let d=h;n&&(d=yh(h,i));const f=le(p),m=aP({inputs:{x:c},attrs:{shape:[le(e.shape)/f,f]},backend:r}),g=lP(m,Aa(e.dtype),"sum",r),y=aP({inputs:{x:g},attrs:{shape:d},backend:r});return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),l&&r.disposeIntermediateTensorInfo(c),y}(s,a,i,n)}const fP={kernelName:Wr,backendName:"webgl",kernelFunc:dP};function mP(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{perm:a}=r,i=n,o=s.shape.length,u=new Array(o);for(let e=0;e<u.length;e++)u[e]=s.shape[a[e]];let l;if(i.shouldExecuteOnCPU([s])){const e=i.texData.get(s.dataId).values,t=ez(e,s.shape,s.dtype,a,u);l=i.makeTensorInfo(u,s.dtype),i.texData.get(l.dataId).values=t}else l=pP(s,a,i);return l}const gP={kernelName:ls,backendName:"webgl",kernelFunc:mP},yP=1e3;function bP({a:e,b:t,transposeA:n,transposeB:r,backend:s,bias:a=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:u=null}){const l=e.shape.length,c=t.shape.length,h=n?e.shape[l-2]:e.shape[l-1],p=r?t.shape[c-1]:t.shape[c-2],d=n?e.shape[l-1]:e.shape[l-2],f=r?t.shape[c-2]:t.shape[c-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=le(m),b=le(g),x=bu(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([d,f]);ie(h===p,(()=>`Error in matMul: inner shapes (${h}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${r} must match.`));const w=n?[y,h,d]:[y,d,h],v=r?[b,f,p]:[b,p,f],k=aP({inputs:{x:e},backend:s,attrs:{shape:w}}),I=aP({inputs:{x:t},backend:s,attrs:{shape:v}}),N=[k,I],S=Math.max(y,b),T=n?k.shape[1]:k.shape[2],C=null!=a,$=null!=i,E="leakyrelu"===u,A=null!=u?Zz(u,!0):null;let R;if((1===d||1===f)&&T>yP&&!1===(C||$||E||null!=A)){let e=k,t=I;n&&(e=mP({inputs:{x:k},backend:s,attrs:{perm:[0,2,1]}}),N.push(e)),r&&(t=mP({inputs:{x:I},backend:s,attrs:{perm:[0,2,1]}}),N.push(t));const a=1===f;let i=e;1!==f&&(i=aP({inputs:{x:e},backend:s,attrs:{shape:[S,T,1]}}),N.push(i));const o=1===f?2:1;let u=t;a&&(u=aP({inputs:{x:t},backend:s,attrs:{shape:[S,1,T]}}),N.push(u));const l=rP({inputs:{a:i,b:u},backend:s});R=dP({inputs:{x:l},backend:s,attrs:{axis:o,keepDims:!0}}),N.push(l)}else{const u=Ea(e.dtype,t.dtype),l=new Qz(w,v,[S,d,f],n,r,C,A,$,E),c=[k,I];if(null!=a&&c.push(a),$&&c.push(i),E){const e=s.makeTensorInfo([],"float32",Ys(o,"float32"));c.push(e),N.push(e)}R=s.runWebGLProgram(l,c,u)}const O=aP({inputs:{x:R},backend:s,attrs:{shape:x}});N.push(R);for(const e of N)s.disposeIntermediateTensorInfo(e);return O}const xP={kernelName:bs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:i,preluActivationWeights:o}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:h}=r;return bP({a:s,b:a,transposeA:u,transposeB:l,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:h,activation:c})}},wP="return abs(x);",vP={kernelName:nt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])&&"complex64"!==r.dtype){const e=n.texData.get(r.dataId),t=BL(e.values);return n.makeTensorInfo(r.shape,r.dtype,t)}let s;return s=Ye().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new Sz(r.shape,wP):new hz(r.shape,wP),n.runWebGLProgram(s,[r],r.dtype)}},kP=Yz({opSnippet:pz+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n"}),IP={kernelName:rt,backendName:"webgl",kernelFunc:kP},NP=Yz({opSnippet:pz+"\n if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));"}),SP={kernelName:st,backendName:"webgl",kernelFunc:NP},TP="return a + b;",CP=Jz({opSnippet:TP,packedOpSnippet:TP,supportsComplex:!0,cpuKernelImpl:oL}),$P={kernelName:at,backendName:"webgl",kernelFunc:CP};class EP{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map(((e,t)=>`T${t}`));const n=[];this.variableNames.forEach((e=>{n.push(`float v${e} = get${e}AtOutCoords();`)}));const r=this.variableNames.map((e=>`v${e}`)).join(" + ");this.userCode=`\n void main() {\n ${n.join("\n ")}\n\n float result = ${r};\n setOutput(result);\n }\n `}}class AP{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map(((e,t)=>`T${t}`));const n=[];this.variableNames.forEach((e=>{n.push(`vec4 v${e} = get${e}AtOutCoords();`)}));const r=this.variableNames.map((e=>`v${e}`)).join(" + ");this.userCode=`\n void main() {\n ${n.join("\n ")}\n\n vec4 result = ${r};\n setOutput(result);\n }\n `}}const RP={kernelName:it,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r}=t,s=n;if(1===s.length)return Pz({inputs:{x:s[0]},backend:r});if(s.length>Ye().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const t=Math.floor(s.length/2),n=e({inputs:s.slice(0,t),backend:r}),a=e({inputs:s.slice(t),backend:r});return e({inputs:[n,a],backend:r})}const a=s.map((e=>e.dtype)).reduce(((e,t)=>Ea(e,t))),i=s.map((e=>e.shape)),o=Ye().getBool("WEBGL_PACK")?new AP(s[0].shape,i):new EP(s[0].shape,i);return r.runWebGLProgram(o,s,a)}},OP={kernelName:ot,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r,o=s.shape.length,u=we(a,s.shape);let l=u;const c=xh(l,o);let h=s;null!=c&&(h=mP({inputs:{x:s},backend:n,attrs:{perm:c}}),l=vh(l.length,o)),bh("all",l,o);const[p,d]=gh(h.shape,l),f=aP({inputs:{x:h},backend:n,attrs:{shape:[-1,le(d)]}}),m=lP(f,f.dtype,"all",n);let g;return g=aP(i?{inputs:{x:m},backend:n,attrs:{shape:yh(p,u)}}:{inputs:{x:m},backend:n,attrs:{shape:p}}),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}},FP={kernelName:ut,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r,o=s.shape.length,u=we(a,s.shape);let l=u;const c=xh(l,o);let h=s;null!=c&&(h=mP({inputs:{x:s},backend:n,attrs:{perm:c}}),l=vh(l.length,o)),bh("any",l,o);const[p,d]=gh(h.shape,l),f=aP({inputs:{x:h},backend:n,attrs:{shape:[-1,le(d)]}}),m=lP(f,f.dtype,"any",n);let g;return g=aP(i?{inputs:{x:m},backend:n,attrs:{shape:yh(p,u)}}:{inputs:{x:m},backend:n,attrs:{shape:p}}),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}};class _P{constructor(e,t,n){this.variableNames=["A"];const{windowSize:r,batchSize:s,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[s,a];const i="max"===t?">":"<",o=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${r};\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < ${r}; i++) {\n int inIdx = ${o};\n float candidate = getA(batch, inIdx);\n if (candidate ${i} bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n `}}class DP{constructor(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,ie(e.length>2,(()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`));const s=e[e.length-1],a=Math.ceil(s/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");const i=this.outputShape,o=i.length,u=IM(o),l=rz("coords",o);let c,h;if(1===a){h=o+1;const e=IM(h);c=`\n ${e} sourceLocR = ${e}(${l.join()}, 0);\n ++${l[o-1]};\n ${e} sourceLocG = ${e}(${l.join()}, 0);\n ++${l[o-2]};\n ${e} sourceLocA = ${e}(${l.join()}, 0);\n --${l[o-1]};\n ${e} sourceLocB = ${e}(${l.join()}, 0);\n --${l[o-2]};`}else h=o,c=`\n ${u} sourceLocR = coords;\n ++${l[o-1]};\n ${u} sourceLocG = coords;\n ++${l[o-2]};\n ${u} sourceLocA = coords;\n --${l[o-1]};\n ${u} sourceLocB = coords;\n --${l[o-2]};`;const p=["x","y","z","w","u","v"].slice(0,h),d="."+p[h-1],f=p.map((e=>"int "+e)),m=rz("sourceLocR",h-1).concat("inIdx.r"),g=rz("sourceLocG",h-1).concat("inIdx.g"),y=rz("sourceLocB",h-1).concat("inIdx.b"),b=rz("sourceLocA",h-1).concat("inIdx.a"),x="max"===n?"greaterThan":"lessThan",w=r?"":`\n inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),\n getBestIndicesAChannel(${g.join()}),\n getBestIndicesAChannel(${y.join()}),\n getBestIndicesAChannel(${b.join()})));`,v=`vec4(\n getAChannel(${m.join()}),\n hasNextCol ? getAChannel(${g.join()}) : 0.,\n hasNextRow ? getAChannel(${y.join()}) : 0.,\n hasNextRow && hasNextCol ? getAChannel(${b.join()}) : 0.)`,k=r?"":`\n float getBestIndicesAChannel(${f.join()}) {\n return getChannel(getBestIndicesA(${p.join()}),\n vec2(${p.slice(-2).join()}));\n }`;this.userCode=`\n float getAChannel(${f.join()}) {\n return getChannel(getA(${p.join()}),\n vec2(${p.slice(-2).join()}));\n }\n ${k}\n void main() {\n ${u} coords = getOutputCoords();\n bool hasNextCol = ${l[o-1]} < ${i[o-1]-1};\n bool hasNextRow = ${l[o-2]} < ${i[o-2]-1};\n ${c}\n ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},\n sourceLocB${d}, sourceLocA${d}) * ${t};\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = ${v};\n\n for (int i = 0; i < ${t}; i++) {\n inIdx = srcIdx;\n ${w}\n vec4 candidate = ${v};\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4(${x}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n `}}function MP(e,t,n,r=null){let s=t.shape[0],a=t.shape[1];null!=r&&(s=r.shape[0],a=r.shape[1]);const i=fm(a),o={windowSize:i,inSize:a,batchSize:s,outSize:Math.ceil(a/i)},u=new _P(o,n,null==r),l=[t];null!=r&&l.push(r);const c=e.runWebGLProgram(u,l,"int32");if(1===c.shape[1])return c;const h=MP(e,t,n,c);return e.disposeIntermediateTensorInfo(c),h}function LP(e,t,n,r=null){const s=null!=r?r.shape:t.shape,a=fm(s[s.length-1]),i=new DP(s,a,n,null==r),o=null==r?[t]:[t,r],u=e.runWebGLProgram(i,o,"int32");if(u.shape.length===t.shape.length){const r=LP(e,t,n,u);return e.disposeIntermediateTensorInfo(u),r}return u}function zP(e,t,n,r){const s=[n];if(bh("arg"+r.charAt(0).toUpperCase()+r.slice(1),s,t.shape.length),!Ye().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const n=[],a=e.texData.get(t.dataId);let i=t;null!==a&&a.isPacked&&(i=e.unpackTensor(t),n.push(i));const[o,u]=gh(i.shape,s),l=le(u),c=aP({inputs:{x:i},backend:e,attrs:{shape:[-1,l]}});n.push(c);const h=MP(e,c,r);n.push(h);const p=aP({inputs:{x:h},backend:e,attrs:{shape:o}});return n.forEach((t=>e.disposeIntermediateTensorInfo(t))),p}return LP(e,t,r)}const PP={kernelName:lt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;let i=we(a,s.shape);const o=xh(i,s.shape.length);let u=s;const l=[];null!=o&&(u=mP({inputs:{x:s},backend:n,attrs:{perm:o}}),l.push(u),i=vh(i.length,u.shape.length)),bh("argMax",[i[0]],u.shape.length);const c=zP(n,u,i[0],"max");return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}},BP={kernelName:ct,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;let i=we(a,s.shape);const o=xh(i,s.shape.length);let u=s;const l=[];null!=o&&(u=mP({inputs:{x:s},backend:n,attrs:{perm:o}}),l.push(u),i=vh(i.length,u.shape.length)),bh("argMin",[i[0]],u.shape.length);const c=zP(n,u,i[0],"min");return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}},WP=Yz({opSnippet:pz+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n"}),UP={kernelName:ht,backendName:"webgl",kernelFunc:WP},VP=Yz({opSnippet:pz+"return log(x + sqrt(x * x + 1.0));"}),GP={kernelName:pt,backendName:"webgl",kernelFunc:VP},jP=Yz({opSnippet:pz+"\n return atan(x);\n"}),HP={kernelName:dt,backendName:"webgl",kernelFunc:jP},qP=Jz({opSnippet:Dz+"\n return atan(a, b);\n",packedOpSnippet:"\n vec4 result = atan(a, b);\n bvec4 isNaNA = isnan(a);\n bvec4 isNaNB = isnan(b);\n bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\n "+Lz+"\n return result;\n"}),KP={kernelName:mt,backendName:"webgl",kernelFunc:qP},XP=Yz({opSnippet:pz+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;"}),YP={kernelName:ft,backendName:"webgl",kernelFunc:XP};class JP{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const a=e.filterWidth,i=e.strideHeight,o=e.strideWidth,u=e.dilationHeight,l=e.dilationWidth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,p=e.padInfo.top,d=e.padInfo.left;this.outputShape=e.outShape;const f="avg"===t,m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let y="0.0";if(f||(y="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n const ivec2 strides = ivec2(${i}, ${o});\n const ivec2 pads = ivec2(${p}, ${d});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < ${c};\n wR += ${u}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${h};\n wC += ${l}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${t} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${r?s?m:g:`wR * ${h} + wC`};\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `)}let b=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(b="avgValue / max(count, 1.0)");const x=4*Math.floor(a/4),w=a%4,v=`\n if (${f}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec2 strides = ivec2(${i}, ${o});\n const ivec2 pads = ivec2(${p}, ${d});\n const float initializationValue = ${y};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= ${e.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4(${y});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < ${c};\n wR += ${u}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${x}; wC += 4) {\n int xC = xCCorner + wC * ${l};\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${l}, d),\n getValue(batch, xR, xC + 2 * ${l}, d),\n getValue(batch, xR, xC + 3 * ${l}, d)\n );\n\n ${v}\n }\n\n int xC = xCCorner + ${x};\n if (${1===w}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${v}\n } else if (${2===w}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${l}, d),\n initializationValue,\n initializationValue\n );\n\n ${v}\n } else if (${3===w}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${l}, d),\n getValue(batch, xR, xC + 2 * ${l}, d),\n initializationValue\n );\n\n ${v}\n }\n }\n setOutput(${b});\n }\n `}}class ZP{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const a=e.filterWidth,i=e.strideDepth,o=e.strideHeight,u=e.strideWidth,l=e.dilationDepth,c=e.dilationHeight,h=e.dilationWidth,p=e.effectiveFilterDepth,d=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;const b="avg"===t;let x="0.0";if(b||(x="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n const ivec3 strides =\n ivec3(${i}, ${o}, ${u});\n const ivec3 pads = ivec3(${m}, ${g}, ${y});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < ${p};\n wD += ${l}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${d};\n wR += ${c}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${f};\n wC += ${h}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${t} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${r?s?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${d} * ${f} +\n wR * ${f} + wC`};\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `)}let w=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(w="avgValue / max(count, 1.0)");const v=4*Math.floor(a/4),k=a%4,I=`\n if (${b}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec3 strides =\n ivec3(${i}, ${o}, ${u});\n const ivec3 pads = ivec3(${m}, ${g}, ${y});\n const float initializationValue = ${x};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= ${e.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4(${x});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < ${p};\n wD += ${l}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${d};\n wR += ${c}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${v}; wC += 4) {\n int xC = xCCorner + wC * ${h};\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${h}, ch),\n getValue(batch, xD, xR, xC + 2 * ${h}, ch),\n getValue(batch, xD, xR, xC + 3 * ${h}, ch)\n );\n\n ${I}\n }\n\n int xC = xCCorner + ${v};\n if (${1===k}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${I}\n } else if (${2===k}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${h}, ch),\n initializationValue,\n initializationValue\n );\n\n ${I}\n } else if (${3===k}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${h}, ch),\n getValue(batch, xD, xR, xC + 2 * ${h}, ch),\n initializationValue\n );\n\n ${I}\n }\n }\n }\n setOutput(${w});\n }\n `}}const QP={kernelName:gt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t;iM(s,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:u}=r;ie(yc(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const l=oc(s.shape,a,i,1,o,u);if(1===l.filterWidth&&1===l.filterHeight&&pe(l.inShape,l.outShape))return Pz({inputs:{x:s},backend:n});const c=new JP(l,"avg",!1);return n.runWebGLProgram(c,[s],"float32")}},eB={kernelName:bt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:u,dataFormat:l}=r,c=uc(s.shape,a,i,[1,1,1],o,u,l),h=new ZP(c,"avg",!1);return n.runWebGLProgram(h,[s],"float32")}};class tB{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=o-1-e.padInfo.top,c=u-1-e.padInfo.left,h=1/(t*n);this.userCode=`\n const ivec2 pads = ivec2(${l}, ${c});\n const float avgMultiplier = float(${h});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${o};\n wR += ${a}) {\n float dyR = float(dyRCorner + wR) / ${r}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${u};\n wC+= ${i}) {\n float dyC = float(dyCCorner + wC) / ${s}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n `}}class nB{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,u=e.dilationHeight,l=e.dilationWidth,c=e.effectiveFilterDepth,h=e.effectiveFilterHeight,p=e.effectiveFilterWidth,d=c-1-e.padInfo.front,f=h-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*r);this.userCode=`\n const ivec3 pads = ivec3(${d}, ${f}, ${m});\n const float avgMultiplier = float(${g});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < ${c};\n wD += ${o}) {\n float dyD = float(dyDCorner + wD) / ${s}.0;\n\n if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${h};\n wR += ${u}) {\n float dyR = float(dyRCorner + wR) / ${a}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${p};\n wC += ${l}) {\n float dyC = float(dyCCorner + wC) / ${i}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const rB={kernelName:xt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,i=a,{filterSize:o,strides:u,pad:l,dimRoundingMode:c}=r,h=uc(i.shape,o,u,[1,1,1],l,c),p=new nB(h);return n.runWebGLProgram(p,[s],i.dtype)}},sB={kernelName:yt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,i=a;iM([s,a],"avgPoolGrad");const{filterSize:o,strides:u,pad:l}=r,c=oc(i.shape,o,u,1,l),h=new tB(c);return n.runWebGLProgram(h,[s],i.dtype)}},aB={kernelName:wt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:i,transposeB:o}=r;return bP({a:s,b:a,transposeA:i,transposeB:o,backend:n})}};class iB{constructor(e,t,n,r,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],bu(e,t),bu(e,n);let i="0.0";null!=r&&(bu(e,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";null!=s&&(bu(e,s),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = ${i};\n float scale = ${o};\n float inv = scale * inversesqrt(variance + float(${a}));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n `}}class oB{constructor(e,t,n,r,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],bu(e,t),bu(e,n);let i="vec4(0.0)";null!=r&&(bu(e,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";null!=s&&(bu(e,s),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n void main() {\n vec4 offset = ${i};\n vec4 scale = ${o};\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4(${a}));\n\n setOutput((x - mean) * inv + offset);\n }\n `}}const uB={kernelName:fn,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,mean:s,variance:a,offset:i,scale:o}=e;ie(s.shape.length===a.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),ie(null==i||s.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),ie(null==o||s.shape.length===o.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));let{varianceEpsilon:u}=n;null==u&&(u=.001);const l=[r,s,a];let c=null;null!=i&&(c=i.shape,l.push(i));let h=null;null!=o&&(h=o.shape,l.push(o));const p=Ye().getBool("WEBGL_PACK_NORMALIZATION")?new oB(r.shape,s.shape,a.shape,c,h,u):new iB(r.shape,s.shape,a.shape,c,h,u);return t.runWebGLProgram(p,l,l[0].dtype)}};class lB{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=IM(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const n=function(e){if(1===e)return"sourceLoc";if(e<=6)return cB.slice(0,e).map((e=>"sourceLoc."+e)).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}(this.rank);let r;r=`\n ${t} sourceLoc;\n ${t} coords = getOutputCoords();\n ${e.map(((e,t)=>`sourceLoc.${cB[t]} = start[${t}] + coords.${cB[t]};`)).join("\n")}\n `,this.userCode=`\n void main() {\n ${r}\n setOutput(getSource(${n}));\n }\n `}}const cB=["x","y","z","w","u","v"];class hB{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const t=IM(this.rank),n=rz("coords",this.rank),r=rz("sourceLoc",this.rank),s=1===this.rank?"sourceLoc":`vec2(${r.slice(-2).join()})`,a=`getChannel(getSource(${r.join()}), ${s})`,i=`\n result.x = ${a};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${r[this.rank-1]};\n result.y = ${a};\n --${r[this.rank-1]};\n }\n `,o=1===this.rank?"":`\n --${n[this.rank-1]};\n if (++${n[this.rank-2]} < ${e[this.rank-2]}) {\n ++${r[this.rank-2]};\n result.z = ${a};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${r[this.rank-1]};\n result.w = ${a};\n }\n }\n `,u=this.rank<=4?`sourceLoc = coords +\n ${t}(${e.map(((e,t)=>`start[${t}]`)).join()});`:e.map(((e,t)=>`${r[t]} = ${n[t]} + start[${t}];`)).join("\n");this.userCode=`\n void main() {\n ${t} coords = getOutputCoords();\n ${t} sourceLoc;\n ${u}\n vec4 result = vec4(0.);\n ${i}\n ${o}\n setOutput(result);\n }\n `}}function pB(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:i}=r,[o,u]=El(s,a,i);if(ml(s,o,u),0===le(u))return n.makeTensorInfo(u,s.dtype,[]);if(n.shouldExecuteOnCPU([s])||"string"===s.dtype){const e=n.texData.get(s.dataId),t=WL(e.values,o,u,s.shape,s.dtype);return n.makeTensorInfo(u,s.dtype,t)}const{isPacked:l}=n.texData.get(s.dataId),c=Cl(s.shape,o,u);if(l||!c){const e=Ye().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new hB(u):new lB(u),t=[o];return n.runWebGLProgram(e,[s],s.dtype,t)}return n.uploadToGPU(s.dataId),function(e,t,n,r){const s=r.texData.get(e.dataId),a=r.makeTensorInfo(n,e.dtype),i=r.texData.get(a.dataId);Object.assign(i,s),i.refCount=1,i.shape=n,i.dtype=e.dtype;let o=$l(t,De(e.shape));s.slice&&(o+=s.slice.flatOffset),i.slice={flatOffset:o,origDataId:s.slice&&s.slice.origDataId||e.dataId};const u=r.dataRefCount.get(i.slice.origDataId)||1;return r.dataRefCount.set(i.slice.origDataId,u+1),a}(s,o,u,n)}const dB={kernelName:_r,backendName:"webgl",kernelFunc:pB},fB={kernelName:vt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:i}=r;ie(s.shape.length<=4,(()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"));const o=a.reduce(((e,t)=>e*t)),u=gm(s.shape,a,o),l=ym(u.length,a.length),c=bm(s.shape,a,o),h=xm(i,a.length),p=wm(c,i,a.length),d=[],f=aP({inputs:{x:s},backend:n,attrs:{shape:u}}),m=mP({inputs:{x:f},backend:n,attrs:{perm:l}}),g=aP({inputs:{x:m},backend:n,attrs:{shape:c}}),y=pB({inputs:{x:g},backend:n,attrs:{begin:h,size:p}});return d.push(f),d.push(m),d.push(g),d.forEach((e=>n.disposeIntermediateTensorInfo(e))),y}},mB={kernelName:kt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:i}=r,o=n.readSync(s.dataId),u=n.readSync(a.dataId),l=uL(o,u,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,l)}},gB={kernelName:It,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{a:r,b:s}=t,a=Ye().getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=Ye().getNumber("WEBGL_VERSION");if(n.shouldExecuteOnCPU([r,s])||1===i){const e=n.texData.get(r.dataId).values,t=n.texData.get(s.dataId).values,[a,i]=cL(r.shape,s.shape,e,t,r.dtype),o=n.makeTensorInfo(i,r.dtype);return n.texData.get(o.dataId).values=a,o}let o;return o=a?new zz("\n int r = int(a.r) & int(b.r);\n int g = int(a.g) & int(b.g);\n int rb = int(a.b) & int(b.b);\n int ra = int(a.a) & int(b.a);\n return vec4(r, g, rb, ra);\n",r.shape,s.shape,!1):new Mz("\n return float(int(a.r) & int(b.r));\n",r.shape,s.shape),n.runWebGLProgram(o,[r,s],r.dtype)}},yB={kernelName:St,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:r,s1:s}=t,a=n.readSync(r.dataId),i=n.readSync(s.dataId),o=bu(Array.from(a),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},bB=Jz({opSnippet:"return float(a != b);",cpuKernelImpl:RL,dtype:"bool"}),xB={kernelName:tr,backendName:"webgl",kernelFunc:bB};function wB(e){const{inputs:t,backend:n}=e,{input:r}=t;return Pz({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.real},backend:n})}const vB={kernelName:yr,backendName:"webgl",kernelFunc:wB},kB={kernelName:Tt,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r,attrs:s}=t,{x:a}=n,{dtype:i}=s;if("complex64"===i){if("complex64"===a.dtype)return Pz({inputs:{x:a},backend:r});const t=up(a.shape),n=e({inputs:{x:a},backend:r,attrs:{dtype:"float32"}}),s=Wz({inputs:{real:n,imag:t},backend:r});return t.dispose(),r.disposeIntermediateTensorInfo(n),s}if("complex64"===a.dtype){const t=wB({inputs:{input:a},backend:r}),n=e({inputs:{x:t},backend:r,attrs:{dtype:i}});return r.disposeIntermediateTensorInfo(t),n}if(!Te(a.dtype,i)){const e=Pz({inputs:{x:a},backend:r});return{dataId:e.dataId,shape:e.shape,dtype:i}}if(r.shouldExecuteOnCPU([a])){const e=r.texData.get(a.dataId).values,[t,n,s]=hL(e,a.shape,a.dtype,i);return r.makeTensorInfo(t,n,s)}if("int32"===i)return function(e,t){const n=new hz(e.shape,"return float(int(x));"),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}(a,r);if("bool"===i){const e=r.makeTensorInfo([],"bool",ke("bool",1)),t=bB({inputs:{a,b:e},backend:r});return r.disposeIntermediateTensorInfo(e),t}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${i}`)}},IB="return ceil(x);",NB=Yz({opSnippet:IB,packedOpSnippet:IB,cpuKernelImpl:pL}),SB={kernelName:Ct,backendName:"webgl",kernelFunc:NB};class TB{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}}class CB{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}}const $B={kernelName:$t,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{clipValueMin:a,clipValueMax:i}=r;let o;o=Ye().getBool("WEBGL_PACK_CLIP")?new CB(s.shape):new TB(s.shape);const u=[[a],[i]];return n.runWebGLProgram(o,[s],s.dtype,u)}};class EB{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "}}function AB(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}const RB={kernelName:At,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,s=n.texData.get(r.dataId),a=new EB(r.shape),i=[AB(r,s.complexTensorInfos.real),AB(r,s.complexTensorInfos.imag)];return n.runWebGLProgram(a,i,i[0].dtype)}};class OB{constructor(e){this.outputShape=[],this.outputShape=om(e,1),this.variableNames=e.map(((e,t)=>`T${t}`));const t=new Array(e.length-1);t[0]=e[0][1];for(let n=1;n<t.length;n++)t[n]=t[n-1]+e[n][1];const n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let e=1;e<t.length;e++){const r=t[e-1];n.push(`else if (yC < ${t[e]}) setOutput(getT${e}(yR, yC-${r}));`)}const r=t.length,s=t[t.length-1];n.push(`else setOutput(getT${r}(yR, yC-${s}));`),this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n ${n.join("\n ")}\n }\n `}}class FB{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=om(e,t);const n=this.outputShape,r=n.length,s=IM(r),a=rz("coords",r),i=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map(((e,t)=>`T${t}`));const o=new Array(e.length-1);o[0]=e[0][t];for(let n=1;n<o.length;n++)o[n]=o[n-1]+e[n][t];const u=i[t],l=i.slice(-2),c=i.join();let h=`if (${u} < ${o[0]}) {\n return getChannel(\n getT0(${c}), vec2(${l.join()}));\n }`;for(let e=1;e<o.length;e++){const t=o[e-1];h+=`\n if (${u} < ${o[e]} && ${u} >= ${o[e-1]}) {\n return getChannel(\n getT${e}(${_B(i,u,t)}),\n vec2(${_B(l,u,t)}));\n }`}const p=o.length,d=o[o.length-1];h+=`\n return getChannel(\n getT${p}(${_B(i,u,d)}),\n vec2(${_B(l,u,d)}));`,this.userCode=`\n float getValue(${i.map((e=>"int "+e))}) {\n ${h}\n }\n\n void main() {\n ${s} coords = getOutputCoords();\n vec4 result = vec4(getValue(${a}), 0., 0., 0.);\n\n ${a[r-1]} = ${a[r-1]} + 1;\n if (${a[r-1]} < ${n[r-1]}) {\n result.g = getValue(${a});\n }\n\n ${a[r-2]} = ${a[r-2]} + 1;\n if (${a[r-2]} < ${n[r-2]}) {\n result.a = getValue(${a});\n }\n\n ${a[r-1]} = ${a[r-1]} - 1;\n if (${a[r-2]} < ${n[r-2]} &&\n ${a[r-1]} < ${n[r-1]}) {\n result.b = getValue(${a});\n }\n setOutput(result);\n }\n `}}function _B(e,t,n){const r=e.indexOf(t);return e.map(((e,t)=>t===r?`${e} - ${n}`:e)).join()}function DB(e){const{inputs:t,backend:n}=e,{input:r}=t;return Pz({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.imag},backend:n})}const MB={kernelName:vn,backendName:"webgl",kernelFunc:DB};function LB(e,t,n){const r=e[0].dtype;if("complex64"===r){const r=e.map((e=>wB({inputs:{input:e},backend:n}))),s=e.map((e=>DB({inputs:{input:e},backend:n}))),a=LB(r,t,n),i=LB(s,t,n),o=Wz({inputs:{real:a,imag:i},backend:n});return r.forEach((e=>n.disposeIntermediateTensorInfo(e))),s.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(i),o}let s=n.shouldExecuteOnCPU(e);if("string"===r&&(s=!0),s){const s=e.map((e=>{const r=le(e.shape.slice(t));return aP({inputs:{x:e},backend:n,attrs:{shape:[-1,r]}})})),a=s.map((e=>({vals:n.readSync(e.dataId),shape:e.shape}))),i=om(s.map((e=>e.shape)),1),o=1===s[0].shape[0],u=dL(a,i,r,o),l=om(e.map((e=>e.shape)),t),c=n.makeTensorInfo(l,r,u);return s.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}const a=e.filter((e=>le(e.shape)>0)),i=Ye().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&a[0].shape.length>1;if(1===a.length){const t=i?new hz(e[0].shape,bz):new Sz(e[0].shape,bz);return n.runWebGLProgram(t,e,r)}const o=Ye().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(a.length>o){const e=[];for(let r=0;r<a.length;r+=o){const s=a.slice(r,r+o);e.push(LB(s,t,n))}const r=LB(e,t,n);for(const t of e)n.disposeIntermediateTensorInfo(t);return r}if(i){const e=new FB(a.map((e=>e.shape)),t);return n.runWebGLProgram(e,a,r)}const{tensors2D:u,outShape:l}=function(e,t,n){const r=om(e.map((e=>e.shape)),t);return{tensors2D:e.map((e=>aP({inputs:{x:e},attrs:{shape:[-1,le(e.shape.slice(t))]},backend:n}))),outShape:r}}(a,t,n),c=new OB(u.map((e=>e.shape))),h=n.runWebGLProgram(c,u,r);u.forEach((e=>n.disposeIntermediateTensorInfo(e)));const p=aP({inputs:{x:h},attrs:{shape:l},backend:n});return n.disposeIntermediateTensorInfo(h),p}function zB(e){const{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=we(s,t[0].shape)[0];im(t.map((e=>e.shape)),a);const i=om(t.map((e=>e.shape)),a);if(0===le(i))return n.makeTensorInfo(i,t[0].dtype,[]);const o=t.filter((e=>le(e.shape)>0));return 1===o.length?Pz({inputs:{x:o[0]},backend:n}):LB(o,a,n)}const PB={kernelName:Rt,backendName:"webgl",kernelFunc:zB};class BB{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const a=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,u=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,h=e.filterHeight,p=e.filterWidth,d=4*Math.floor(e.inChannels/4),f=e.inChannels%4,m="channelsLast"===e.dataFormat,g=m?1:2,y=m?2:3,b=m?3:1;let x="",w="";n&&(x=r?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:s?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,w="result = activation(result);");const v=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${x}\n\n const ivec2 strides = ivec2(${o}, ${u});\n const ivec2 pads = ivec2(${a}, ${i});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[${b}];\n\n ivec2 xRCCorner =\n ivec2(coords[${g}], coords[${y}]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${h}; wR++) {\n int xR = xRCorner + wR * ${l};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${p}; wC++) {\n int xC = xCCorner + wC * ${c};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${d}; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if (${m}) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if (${1===f}) {\n\n if (${m}) {\n dotProd +=\n getX(batch, xR, xC, ${d}) *\n getW(wR, wC, ${d}, d2);\n } else {\n dotProd +=\n getX(batch, ${d}, xR, xC) *\n getW(wR, wC, ${d}, d2);\n }\n\n } else if (${2===f}) {\n vec2 wValues = vec2(\n getW(wR, wC, ${d}, d2),\n getW(wR, wC, ${d} + 1, d2)\n );\n\n if (${m}) {\n vec2 xValues = vec2(\n getX(batch, xR, xC, ${d}),\n getX(batch, xR, xC, ${d} + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, ${d}, xR, xC),\n getX(batch, ${d} + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if (${3===f}) {\n vec3 wValues = vec3(\n getW(wR, wC, ${d}, d2),\n getW(wR, wC, ${d} + 1, d2),\n getW(wR, wC, ${d} + 2, d2)\n );\n\n if (${m}) {\n vec3 xValues = vec3(\n getX(batch, xR, xC, ${d}),\n getX(batch, xR, xC, ${d} + 1),\n getX(batch, xR, xC, ${d} + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, ${d}, xR, xC),\n getX(batch, ${d} + 1, xR, xC),\n getX(batch, ${d} + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n ${v}\n ${w}\n setOutput(result);\n }\n `}}class WB{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,u=e.dilationHeight,l=e.dilationWidth,c=e.filterDepth,h=e.filterHeight,p=e.filterWidth,d=4*Math.floor(e.inChannels/4),f=e.inChannels%4;this.userCode=`\n const ivec3 strides = ivec3(${s}, ${a}, ${i});\n const ivec3 pads = ivec3(${t}, ${n}, ${r});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < ${c}; wF++) {\n int xF = xFCorner + wF * ${o};\n\n if (xF < 0 || xF >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${h}; wR++) {\n int xR = xRCorner + wR * ${u};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${p}; wC++) {\n int xC = xCCorner + wC * ${l};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${d}; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if (${1===f}) {\n dotProd +=\n getX(batch, xF, xR, xC, ${d}) *\n getW(wF, wR, wC, ${d}, d2);\n } else if (${2===f}) {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, ${d}),\n getX(batch, xF, xR, xC, ${d} + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, ${d}, d2),\n getW(wF, wR, wC, ${d} + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if (${3===f}) {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, ${d}),\n getX(batch, xF, xR, xC, ${d} + 1),\n getX(batch, xF, xR, xC, ${d} + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, ${d}, d2),\n getW(wF, wR, wC, ${d} + 1, d2),\n getW(wF, wR, wC, ${d} + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class UB{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=EM(this.outputShape.length);const a=e.padInfo.left,i=e.strideWidth,o=e.dilationWidth,u=e.filterHeight,l=e.filterWidth,c=l;let h="\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";for(let e=0;e<l;e++)h+=`\n vec4 xTexelC${2*e};\n int xTexelC${2*e}Ready;\n vec4 xTexelC${2*e+1};\n int xTexelC${2*e+1}Ready;\n vec4 xC${e};`;h+=`\n for (int r = 0; r < ${u}; r++) {\n for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {\n `;for(let e=0;e<l;e++)h+=`\n xTexelC${2*e} = vec4(0.0);\n xTexelC${2*e}Ready = 0;\n xTexelC${2*e+1} = vec4(0.0);\n xTexelC${2*e+1}Ready = 0;\n xC${e} = vec4(0.0);`;h+="\n xR = xRCorner + r * dilations[0];\n if (xR >=0 && xR < inDims[0]) {\n ";for(let t=0;t<(c+1)/2;t++){const n=2*t;if(h+=`\n xC = xCCorner + ${n*o};\n `,1===i){if(n<l&&(a%2==1?(h+=`\n xCOffset = xC + 1;\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n `,h+=1===o&&n>0?`\n xC${n} = vec4(xTexelC${n-2}.zw, xTexelC${n}.xy);\n `:`\n xCOffset = xC + 1 - 2;\n\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n previous.zw = vec2(0.0);\n }\n\n xC${n} = vec4(previous.zw, xTexelC${n}.xy);\n } else {\n xC${n} = vec4(0.0, 0.0, xTexelC${n}.xy);\n }\n `):h+=`\n if (xC >= 0 && xC < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n xC${n} = xTexelC${n};\n `,n+1<l)){const e=a%2==0?te(o):o;o%2==0&&a%2==1||o%2!=0&&a%2!=1?(h+=`\n xCOffset = xC + imod(pads[1], 2) + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n `,h+=o>1?`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${n+1} = vec4(previous.zw, xTexelC${n+1}.xy);\n } else {\n xC${n+1} = vec4(0.0, 0.0, xTexelC${n+1}.xy);\n }\n `:`\n xC${n+1} = vec4(xTexelC${n}.zw, xTexelC${n+1}.xy);\n `):h+=1===e?`\n xC${n+1} = xTexelC${n};\n `:`\n xCOffset = xC + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n+1} = xTexelC${n+1};\n `}}else n<l&&(a%2==1?(h+=`\n xCOffset = xC + 1 - strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xCOffset, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xC + 1, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xC + 2 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n} = vec4(xTexelC${n}.zw, xTexelC${n+1}.zw);\n `,n+1<l&&(h+=`\n final = vec4(0.0);\n xCOffset = xC + 1 + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${n+1} = vec4(xTexelC${n+1}.xy, final.xy);\n `)):(h+=`\n if(xC >= 0 && xC < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n} = vec4(\n xTexelC${n}.xy, xTexelC${n+1}.xy);\n `,n+1<l&&(h+=`\n xC${n+1} = vec4(xTexelC${n}.zw, xTexelC${n+1}.zw);\n `)));n<l&&(h+=`\n wTexel = getW(r, ${n}, d1, d2);\n dotProd += xC${n}.xxzz * vec4(wTexel.xy, wTexel.xy);\n if(d1 + 1 < ${e.inChannels}) {\n dotProd += xC${n}.yyww * vec4(wTexel.zw, wTexel.zw);\n }\n `,n+1<l&&(h+=`\n wTexel = getW(r, ${n+1}, d1, d2);\n dotProd += xC${n+1}.xxzz * vec4(wTexel.xy, wTexel.xy);\n if(d1 + 1 < ${e.inChannels}) {\n dotProd += xC${n+1}.yyww * vec4(wTexel.zw, wTexel.zw);\n }\n `))}h+="\n }\n ",h+="\n }\n ",h+="\n }\n ";let p="",d="";n&&(p=r?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:s?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`vec4 activation(vec4 x) {\n ${n}\n }`,d="result = activation(result);");const f=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${p}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n vec4 dotProd = vec4(0.000000000000001);\n\n ${h}\n\n vec4 result = dotProd - vec4(0.000000000000001);\n ${f}\n ${d}\n setOutput(result);\n }\n `}}class VB{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec4"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=EM(this.outputShape.length);const{dataFormat:n}=t,r=uM(),s="channelsLast"===n,a=s?1:2,i=s?2:3,o=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${e[2]} && pos < ${e[1]}) {`;let u="";for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)u+=`\n blockIndex = rc.z + ${t};\n pos = rc.y + ${e};\n\n ${o}\n offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];\n d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);\n\n if(d0 < inputShape[${a}] && d0 >= 0) {\n // Use custom imod instead mod. On Intel GPU, mod may generate\n // unexpected value.\n // https://github.com/tensorflow/tfjs/issues/5447\n offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];\n d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /\n inChannels);\n\n if(d1 < inputShape[${i}] && d1 >= 0) {\n\n ch = imod(pos, inChannels);\n\n if (${s}) {\n innerDims = vec2(d1, ch);\n result[${2*e+t}] = getChannel(\n getA(rc.x, d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result[${2*e+t}] = getChannel(\n getA(rc.x, ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n `;this.userCode=`\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n ${u}\n\n ${r.output} = result;\n }\n `}}function GB(e,t){const n=e.length;return n>=3?t?[...e.slice(0,-3),e[n-3]*e[n-2],e[n-1]]:[...e.slice(0,-3),e[n-3],e[n-2]*e[n-1]]:!t&&1===n&&e[0]>1?[e[0],1]:null}function jB({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:o=null}){const u=e.shape,l=r.texData.get(e.dataId),c=n.inChannels,h=u[0]*u[1]*u[2],p=n.outChannels,d="channelsLast"===n.dataFormat;let f;const m=[];if(null!=a){const e=GB(a.shape,d);null!=e&&(a=aP({inputs:{x:a},backend:r,attrs:{shape:e}}),m.push(a))}if(null!=s){const e=GB(s.shape,d);null!=e&&(s=aP({inputs:{x:s},backend:r,attrs:{shape:e}}),m.push(s))}if((1!==h&&1!==p||!(c>yP))&&l.isPacked&&d&&null!=l.texture&&u[2]%2!=0&&pe(l.shape.slice(-3),u.slice(-3))){const c=u[0]*u[1]*(u[2]+1),h={dataId:e.dataId,shape:[1,c,n.inChannels],dtype:e.dtype},p=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,ie(HD(l.shape,h.shape),(()=>`packed reshape ${l.shape} to ${h.shape} isn't free`));const d=aP({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});m.push(d);const g=bP({a:h,b:d,backend:r,transposeA:!1,transposeB:!1,bias:s,activation:o,preluActivationWeights:a,leakyreluAlpha:i}),y=r.texData.get(g.dataId);ie(y.isPacked,(()=>"batchMatMul result is expected to be packed")),l.shape=p,y.shape=n.outShape,f=Pz({inputs:{x:g},backend:r}),f.shape=n.outShape,m.push(g)}else{const u=n.outHeight*n.outWidth,l=aP({inputs:{x:e},backend:r,attrs:{shape:d?[n.batchSize,u,n.inChannels]:[n.batchSize,n.inChannels,u]}}),c=aP({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),h=bP({a:d?l:c,b:d?c:l,transposeA:!d,transposeB:!1,backend:r,bias:s,activation:o,preluActivationWeights:a,leakyreluAlpha:i});f=aP({inputs:{x:h},backend:r,attrs:{shape:n.outShape}}),m.push(l),m.push(c),m.push(h)}for(const e of m)r.disposeIntermediateTensorInfo(e);return f}function HB({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:o=null}){const{filterWidth:u,filterHeight:l,inChannels:c,outWidth:h,outHeight:p,dataFormat:d}=n,f="channelsLast"===d,m=u*l*c,g=p*h,y=[n.batchSize,m,g],b=[];if(null!=a){const e=GB(a.shape,f);null!=e&&(a=aP({inputs:{x:a},backend:r,attrs:{shape:e}}),b.push(a))}if(null!=s){const e=GB(s.shape,f);null!=e&&(s=aP({inputs:{x:s},backend:r,attrs:{shape:e}}),b.push(s))}const x=aP({inputs:{x:t},backend:r,attrs:{shape:[1,m,le(t.shape)/m]}});b.push(x);const w=new VB(y,n),v=[e.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],k=r.runWebGLProgram(w,[e],"float32",v),I=aP({inputs:{x:k},backend:r,attrs:{shape:y}});b.push(k),b.push(I);const N=null!=s,S=null!=a,T="leakyrelu"===o,C=o?Zz(o,!0):null,$=new Qz(f?I.shape:x.shape,f?x.shape:I.shape,f?[n.batchSize,g,n.outChannels]:[n.batchSize,n.outChannels,g],!0,!1,N,C,S,T),E=f?[I,x]:[x,I];if(s&&E.push(s),S&&E.push(a),T){const e=r.makeTensorInfo([],"float32",Ys(i,"float32"));E.push(e),b.push(e)}const A=r.runWebGLProgram($,E,"float32"),R=aP({inputs:{x:A},backend:r,attrs:{shape:n.outShape}});b.push(A);for(const e of b)r.disposeIntermediateTensorInfo(e);return R}const qB={kernelName:Ot,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dataFormat:u,dilations:l,dimRoundingMode:c}=r,h=xc(u),p=lc(s.shape,a.shape,i,l,o,c,!1,h);let d;if(1!==p.filterHeight||1!==p.filterWidth||1!==p.dilationHeight||1!==p.dilationWidth||1!==p.strideHeight||1!==p.strideWidth||"SAME"!==p.padInfo.type&&"VALID"!==p.padInfo.type)if(p.strideWidth<=2&&"channelsLast"===h&&Ye().getBool("WEBGL_EXP_CONV")){const e=new UB(p),t=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];d=n.runWebGLProgram(e,[s,a],"float32",t)}else if(Ye().getBool("WEBGL_CONV_IM2COL"))d=HB({x:s,filter:a,convInfo:p,backend:n});else{const e=new BB(p);d=n.runWebGLProgram(e,[s,a],"float32")}else d=jB({x:s,filter:a,convInfo:p,backend:n});const f=aP({inputs:{x:d},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(d),f}};class KB{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a="channelsLast"===e.dataFormat;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${t} - ${r};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${n} - ${s};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n ${a?"float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);":"float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);"}\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class XB{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a="channelsLast"===e.dataFormat,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,u=a?1:2,l=a?2:3,c=a?3:1;this.userCode=`\n const ivec2 pads = ivec2(${i}, ${o});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[${c}];\n\n ivec2 dyCorner = ivec2(coords[${u}], coords[${l}]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / ${r}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n float dyC = float(dyCCorner + wC) / ${s}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${n} - 1 - wC;\n\n for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n\n if (${a}) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class YB{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.padInfo.front,a=e.padInfo.top,i=e.padInfo.left;this.userCode=`\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yF = 0; yF < ${e.outDepth}; yF++) {\n int xF = wF + yF * ${t} - ${s};\n\n if (xF < 0 || xF >= ${e.inDepth}) {\n continue;\n }\n\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${n} - ${a};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${r} - ${i};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class JB{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,u=n-1-e.padInfo.top,l=r-1-e.padInfo.left;this.userCode=`\n const ivec3 pads = ivec3(${o}, ${u}, ${l});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < ${t}; wF++) {\n float dyF = float(dyFCorner + wF) / ${s}.0;\n\n if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = ${t} - 1 - wF;\n\n for (int wR = 0; wR < ${n}; wR++) {\n float dyR = float(dyRCorner + wR) / ${a}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${n} - 1 - wR;\n\n for (int wC = 0; wC < ${r}; wC++) {\n float dyC = float(dyCCorner + wC) / ${i}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${r} - 1 - wC;\n\n for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const ZB={kernelName:Ft,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,pad:o,dataFormat:u,dimRoundingMode:l,filterShape:c}=r,h=xc(u),p=lc(s.shape,c,i,1,o,l,!1,h),d=new KB(p);return n.runWebGLProgram(d,[s,a],"float32")}};class QB{constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=EM(this.outputShape.length);const t=e.filterHeight,n=e.filterWidth,r=t-1-e.padInfo.top,s=n-1-e.padInfo.left;this.userCode=`\n const ivec2 pads = ivec2(${r}, ${s});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n vec4 result = vec4(0.);\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / strides[0];\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n int wCPerm = ${n} - 1 - wC;\n\n float dyC = float(dyCCorner + wC) / strides[1];\n bool idyCVal = (dyC >= 0.0) && (dyC < ${e.outWidth}.0)\n && (fract(dyC) == 0.0);\n int idyC = int(dyC);\n\n float dyC2 = float(dyCCorner + wC + 1) / strides[1];\n bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0)\n && (fract(dyC2) == 0.0);\n int idyC2 = int(dyC2);\n\n if (idyCVal && idyCVal2) {\n for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC, d2);\n vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?\n dySample : getDy(batch, idyR, idyC2, d2);\n\n vec2 dyValue = mod(float(idyC), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.xy += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n\n dyValue = mod(float(idyC2), 2.) == 0. ?\n dySample2.xy : dySample2.zw;\n result.zw += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n } else if (idyCVal) {\n for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC, d2);\n vec2 dyValue = mod(float(idyC), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.xy += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n } else if (idyCVal2) {\n for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC2, d2);\n vec2 dyValue = mod(float(idyC2), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.zw += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n }\n }\n }\n setOutput(result);\n }\n `}}const eW={kernelName:_t,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:i,strides:o,pad:u,dataFormat:l,dimRoundingMode:c}=r,h=xc(l),p=lc(i,a.shape,o,1,u,c,!1,h);if(Ye().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&"channelsLast"===h){const e=[[p.strideHeight,p.strideWidth]],t=new QB(p);return n.runWebGLProgram(t,[s,a],"float32",e)}{const e=new XB(p);return n.runWebGLProgram(e,[s,a],"float32")}}},tW={kernelName:Dt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dilations:u}=r,l=cc(s.shape,a.shape,i,u,o),c=new WB(l);return n.runWebGLProgram(c,[s,a],"float32")}},nW={kernelName:Mt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,pad:o,filterShape:u}=r,l=cc(s.shape,u,i,1,o),c=new YB(l);return n.runWebGLProgram(c,[s,a],"float32")}},rW={kernelName:Lt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:i,strides:o,inputShape:u}=r,l=cc(u,a.shape,o,1,i),c=new JB(l);return n.runWebGLProgram(c,[s,a],"float32")}},sW=Yz({opSnippet:Xz+"\n return cos(x);\n",packedOpSnippet:`\n vec4 result = cos(x);\n bvec4 isNaN = isnan(x);\n ${Lz}\n return result;\n`}),aW={kernelName:zt,backendName:"webgl",kernelFunc:sW},iW=Yz({opSnippet:"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n"}),oW={kernelName:Pt,backendName:"webgl",kernelFunc:iW};class uW{constructor(e,t,n,r,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[a,i,o,u]=e,[l]=t,[c,h]=n;this.outputShape=[l,c,h,u];const p="bilinear"===r?1:0,[d,f]=[i-1+".0",o-1+".0"],[m,g,y]=c>1?[""+(i-1)/(c-1),"(y2-y1) * height_ratio",`y1*${d} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${d}`],[b,x,w]=h>1?[""+(o-1)/(h-1),"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`\n const float height_ratio = float(${m});\n const float width_ratio = float(${b});\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= ${a}) {\n return;\n }\n\n float height_scale = ${g};\n float width_scale = ${x};\n\n float in_y = ${y};\n if( in_y < 0.0 || in_y > ${d} ) {\n setOutput(float(${s}));\n return;\n }\n float in_x = ${w};\n if( in_x < 0.0 || in_x > ${f} ) {\n setOutput(float(${s}));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if(${p} == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n `}}const lW={kernelName:Ut,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:i}=t,{cropSize:o,method:u,extrapolationValue:l}=r,c=new uW(s.shape,a.shape,o,u,l);return n.runWebGLProgram(c,[s,a,i],"float32")}};var cW;!function(e){e.Prod="*",e.Sum="+"}(cW||(cW={}));class hW{constructor(e,t,n,r){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];const s=this.outputShape.length,a=this.op===cW.Prod?"1.0":"0.0",i=n?a:`getX(${pW(s,"coords",this.op)})`,o=this.outputShape[this.outputShape.length-1];let u="",l="";n?(u=r?"end != "+(o-1):"end != 0",l=r?"end + 1":"end - 1"):(u=r?`end + pow2 < ${o}`:"end >= pow2",l=r?"end + pow2":"end - pow2"),this.userCode=`\n void main() {\n ${IM(s)} coords = getOutputCoords();\n int end = ${dW(s,"coords",this.op)};\n float val = ${i};\n int pow2 = int(pow(2.0, index));\n if (${u}) {\n int idx = ${l};\n ${dW(s,"coords",this.op)} = idx;\n val ${this.op}= getX(${pW(s,"coords",this.op)});\n }\n setOutput(val);\n }\n `}}function pW(e,t,n){if(1===e)return`${t}`;if(2===e)return`${t}.x, ${t}.y`;if(3===e)return`${t}.x, ${t}.y, ${t}.z`;if(4===e)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function dW(e,t,n){if(1===e)return`${t}`;if(2===e)return`${t}.y`;if(3===e)return`${t}.z`;if(4===e)return`${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function fW(e,t,n,r,s,a){const i=t.shape.length,o=xh([r],i);let u=t;null!=o&&(u=mP({inputs:{x:t},backend:n,attrs:{perm:o}}));const l=vh(1,i)[0];if(l!==i-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${r}`);const c=u.shape[l];let h=Pz({inputs:{x:u},backend:n});for(let t=0;t<=Math.ceil(Math.log2(c))-1;t++){const r=new hW(e,u.shape,!1,a),s=[[t]],i=h;h=n.runWebGLProgram(r,[h],h.dtype,s),n.disposeIntermediateTensorInfo(i)}if(s){const t=new hW(e,u.shape,s,a),r=h;h=n.runWebGLProgram(t,[h],h.dtype),n.disposeIntermediateTensorInfo(r)}if(null!=o){const e=mP({inputs:{x:h},backend:n,attrs:{perm:wh(o)}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(u),e}return h}const mW={kernelName:Bt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:i,reverse:o}=r;return fW(cW.Prod,s,n,a,i,o)}},gW={kernelName:Wt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:i,reverse:o}=r;return fW(cW.Sum,s,n,a,i,o)}},yW={kernelName:Vt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:i,binaryOutput:o}=r;if(1===s.shape.length){const e=n.readSync(s.dataId),t=n.readSync(a.dataId),r=uL(e,t,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,r)}if(2===s.shape.length){const e=n.bufferSync(s),t=n.bufferSync(a),r=lL(e,t,i,o);return n.makeTensorInfo(r.shape,a.dtype,r.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${s.shape.length}.`)}};class bW{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = ${this.getHeightCoordString()};\n int w = ${this.getWidthCoordString()};\n int d = ${this.getDepthCoordString()};\n\n int in_h = h / ${t};\n int offset_h = imod(h, ${t});\n int in_w = w / ${t};\n int offset_w = imod(w, ${t});\n int offset_d = (offset_h * ${t} + offset_w) *\n ${this.getOutputDepthSize()};\n int in_d = d + offset_d;\n\n float result = ${this.getInputSamplingString()};\n setOutput(result);\n }\n `}getHeightCoordString(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"}getWidthCoordString(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"}getDepthCoordString(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"}getOutputDepthSize(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}const xW={kernelName:Gt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:i}=r,o=s.shape[0],u=("NHWC"===i?s.shape[1]:s.shape[2])*a,l=("NHWC"===i?s.shape[2]:s.shape[3])*a,c=("NHWC"===i?s.shape[3]:s.shape[1])/(a*a),h=new bW("NHWC"===i?[o,u,l,c]:[o,c,u,l],a,i);return n.runWebGLProgram(h,[s],s.dtype)}};class wW{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=EM(this.outputShape.length);const a=e.filterHeight,i=e.filterWidth,o=e.outChannels/e.inChannels;let u="",l="";n&&(u=r?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:s?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,l="result = activation(result);");const c=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${u}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / ${o};\n int q = d2 - d1 * ${o};\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < ${a}; wR++) {\n int xR = xRCorner + wR * dilations[0];\n\n if (xR < 0 || xR >= inDims[0]) {\n continue;\n }\n\n for (int wC = 0; wC < ${i}; wC++) {\n int xC = xCCorner + wC * dilations[1];\n\n if (xC < 0 || xC >= inDims[1]) {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n ${c}\n ${l}\n setOutput(result);\n }\n `}}class vW{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=EM(this.outputShape.length);const a=e.outChannels/e.inChannels,i=e.padInfo.left,o=e.strideWidth,u=e.dilationWidth,l=e.filterHeight,c=e.filterWidth,h=c;let p="\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";for(let e=0;e<c;e++)p+=`\n vec4 xTexelC${2*e};\n int xTexelC${2*e}Ready;\n vec4 xTexelC${2*e+1};\n int xTexelC${2*e+1}Ready;\n vec4 xC${e};`;p+=`\n for (int r = 0; r < ${l}; r++) {\n `;for(let e=0;e<c;e++)p+=`\n xTexelC${2*e} = vec4(0.0);\n xTexelC${2*e}Ready = 0;\n xTexelC${2*e+1} = vec4(0.0);\n xTexelC${2*e+1}Ready = 0;\n xC${e} = vec4(0.0);`;p+="\n xR = xRCorner + r * dilations[0];\n if (xR >=0 && xR < inDims[0]) {\n ";for(let e=0;e<(h+1)/2;e++){const t=2*e;if(p+=`\n xC = xCCorner + ${t*u};\n `,1===o){if(t<c&&(i%2==1?(p+=`\n xCOffset = xC + 1;\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n `,p+=1===u&&t>0?`\n xC${t} = vec4(xTexelC${t-2}.zw, xTexelC${t}.xy);\n `:`\n xCOffset = xC + 1 - 2;\n\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n previous.zw = vec2(0.0);\n }\n\n xC${t} = vec4(previous.zw, xTexelC${t}.xy);\n } else {\n xC${t} = vec4(0.0, 0.0, xTexelC${t}.xy);\n }\n `):p+=`\n if (xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n xC${t} = xTexelC${t};\n `,t+1<c)){const e=i%2==0?te(u):u;u%2==0&&i%2==1||u%2!=0&&i%2!=1?(p+=`\n xCOffset = xC + imod(pads[1], 2) + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n `,p+=u>1?`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${t+1} = vec4(previous.zw, xTexelC${t+1}.xy);\n } else {\n xC${t+1} = vec4(0.0, 0.0, xTexelC${t+1}.xy);\n }\n `:`\n xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.xy);\n `):p+=1===e?`\n xC${t+1} = xTexelC${t};\n `:`\n xCOffset = xC + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t+1} = xTexelC${t+1};\n `}}else t<c&&(i%2==1?(p+=`\n xCOffset = xC + 1 - strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xCOffset, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xC + 1, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xC + 2 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\n `,t+1<c&&(p+=`\n final = vec4(0.0);\n xCOffset = xC + 1 + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${t+1} = vec4(xTexelC${t+1}.xy, final.xy);\n `)):(p+=`\n if(xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t} = vec4(\n xTexelC${t}.xy, xTexelC${t+1}.xy);\n `,t+1<c&&(p+=`\n xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\n `)));t<c&&(p+=`\n wTexel = getW(r, ${t}, d1, q);\n dotProd += xC${t} * vec4(wTexel.xz, wTexel.xz);\n `,t+1<c&&(p+=`\n wTexel = getW(r, ${t+1}, d1, q);\n dotProd += xC${t+1} * vec4(wTexel.xz, wTexel.xz);\n `))}p+="\n }\n ",p+="\n }\n ";let d="",f="";n&&(d=r?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:s?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`vec4 activation(vec4 x) {\n ${n}\n }`,f="result = activation(result);");const m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${d}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / ${a};\n int q = d2 - d1 * ${a};\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n vec4 dotProd = vec4(0.000000000000001);\n\n ${p}\n\n vec4 result = dotProd - vec4(0.000000000000001);\n ${m}\n ${f}\n setOutput(result);\n }\n `}}const kW={kernelName:jt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dilations:u,dimRoundingMode:l}=r;let c=u;null==c&&(c=[1,1]),ie(yc(i,c),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`));const h=lc(s.shape,a.shape,i,c,o,l,!0);let p;p=Ye().getBool("WEBGL_PACK_DEPTHWISECONV")&&h.strideWidth<=2&&h.outChannels/h.inChannels==1?new vW(h):new wW(h);const d=[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth]];return n.runWebGLProgram(p,[s,a],"float32",d)}};class IW{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * ${a} + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${t} - ${r};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${n} - ${s};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class NW{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=t-1-e.padInfo.top,i=n-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`\n const ivec2 pads = ivec2(${a}, ${i});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / ${r}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n float dyC = float(dyCCorner + wC) / ${s}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${n} - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < ${o}; dm++) {\n int d2 = d1 * ${o} + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const SW={kernelName:Ht,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:i,dilations:o,pad:u,dimRoundingMode:l,filterShape:c}=r,h=lc(s.shape,c,i,o,u,l,!0),p=new IW(h);return n.runWebGLProgram(p,[s,a],"float32")}},TW={kernelName:qt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:i,dilations:o,pad:u,dimRoundingMode:l,inputShape:c}=r,h=lc(c,a.shape,i,o,u,l,!0),p=new NW(h);return n.runWebGLProgram(p,[s,a],"float32")}};class CW{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "}}const $W={kernelName:Kt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,s=[...r.shape,...r.shape],a=le(r.shape),i=aP({inputs:{x:r},backend:n,attrs:{shape:[a]}}),o=new CW(a),u=n.runWebGLProgram(o,[i],i.dtype),l=aP({inputs:{x:u},backend:n,attrs:{shape:s}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(u),l}};class EW{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const{inHeight:t,inWidth:n,padInfo:r,strideHeight:s,strideWidth:a,filterHeight:i,filterWidth:o,dilationHeight:u,dilationWidth:l}=e,{top:c,left:h}=r;this.userCode=`\n const ivec2 strides = ivec2(${s}, ${a});\n const ivec2 pads = ivec2(${c}, ${h});\n const float neg_infinity = -3.4e38;\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.w;\n ivec2 outTopLeftCorner =\n coords.yz * strides - pads;\n int hBeg = outTopLeftCorner.x;\n int wBeg = outTopLeftCorner.y;\n\n float curVal = neg_infinity;\n for (int h = 0; h < ${i}; h++) {\n int hIn = hBeg + h * ${u};\n\n if (hIn >= 0 && hIn < ${t}) {\n for (int w = 0; w < ${o}; w++) {\n int wIn = wBeg + w * ${l};\n\n if (wIn >= 0 && wIn < ${n}) {\n float xVal = getX(batch, hIn, wIn, d1);\n float wVal = getW(h, w, d1);\n\n float val = xVal + wVal;\n if (val > curVal) {\n curVal = val;\n }\n }\n }\n }\n }\n\n float result = curVal;\n setOutput(result);\n }\n `}}const AW={kernelName:Xt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:i,pad:o,dilations:u}=r,l=ic(s.shape,a.shape,i,o,"NHWC",u);let c;const h=new EW(l);c=n.runWebGLProgram(h,[s,a],"float32");const p=aP({inputs:{x:c},backend:n,attrs:{shape:l.outShape}});return n.disposeIntermediateTensorInfo(c),p}},RW={kernelName:en,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:i,summedDims:o,idDims:u}=Wm(s,a.length);Vm(i.length,u,a);const{path:l,steps:c}=Gm(o,u),h=c.length;let p=null,d=i.length;const f=[];for(let e=0;e<h;++e){for(const t of c[e]){const{permutationIndices:e,expandDims:r}=Um(d,u[t]);let s;jm(e)?s=a[t]:(s=mP({inputs:{x:a[t]},backend:n,attrs:{perm:e}}),f.push(s));const i=s.shape.slice();for(let e=0;e<r.length;++e)i.splice(r[e],0,1);pe(s.shape,i)||(s=aP({inputs:{x:s},backend:n,attrs:{shape:i}}),f.push(s)),null===p?p=s:(p=rP({inputs:{a:s,b:p},backend:n}),f.push(p))}e<h-1&&(l[e]>=0&&(p=dP({inputs:{x:p},backend:n,attrs:{axis:l[e]-(i.length-d),keepDims:!1}}),f.push(p)),d--)}for(const e of f)e!==p&&n.disposeIntermediateTensorInfo(e);return p}},OW=Yz({opSnippet:"return (x >= 0.0) ? x : (exp(x) - 1.0);",packedOpSnippet:"\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n"}),FW={kernelName:tn,backendName:"webgl",kernelFunc:OW},_W={kernelName:nn,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n}=e,{dy:r,y:s}=t,a=Ye().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new zz("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",r.shape,s.shape):new Mz("return (b >= 0.0) ? a : a * (b + 1.0);",r.shape,s.shape);return n.runWebGLProgram(a,[r,s],r.dtype)}},DW=Jz({opSnippet:"return float(a == b);",packedOpSnippet:"\n return vec4(equal(a, b));\n",dtype:"bool",cpuKernelImpl:fL}),MW={kernelName:sn,backendName:"webgl",kernelFunc:DW},LW=Yz({opSnippet:`\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = ${Im};\n float a1 = ${Nm};\n float a2 = ${Sm};\n float a3 = ${Tm};\n float a4 = ${Cm};\n float a5 = ${$m};\n\n float sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n`}),zW={kernelName:rn,backendName:"webgl",kernelFunc:LW},PW=Yz({opSnippet:Xz+"\n return exp(x);\n",packedOpSnippet:"\n vec4 result = exp(x);\n bvec4 isNaN = isnan(x);\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",cpuKernelImpl:mL,dtype:"float32"}),BW={kernelName:an,backendName:"webgl",kernelFunc:PW};function WW(e){const{inputs:t,attrs:n,backend:r}=e,{dim:s}=n,{input:a}=t,i=a.shape.length,o=a.shape.slice();let u=s;return s<0&&(ie(-(i+1)<=s,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),u=i+s+1),o.splice(u,0,1),aP({inputs:{x:a},backend:r,attrs:{shape:o}})}const UW={kernelName:on,backendName:"webgl",kernelFunc:WW},VW="return exp(x) - 1.0;",GW=Yz({opSnippet:VW,packedOpSnippet:VW,cpuKernelImpl:gL}),jW={kernelName:un,backendName:"webgl",kernelFunc:GW};class HW{constructor(e,t,n){this.variableNames=["real","imag"];const r=t[1];this.outputShape=t;const s=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=n?`${r}.0`:"1.0";let i;if("real"===e)i="return real * expR - imag * expI;";else{if("imag"!==e)throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);i="return real * expI + imag * expR;"}this.userCode=`\n const float exponentMultiplier = ${s};\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n ${i}\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float(${r});\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < ${r}; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / ${a};\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n `}}function qW(e,t,n){const r=n.texData.get(e.dataId),s=le(e.shape),a=e.shape[e.shape.length-1],i=aP({inputs:{x:e},backend:n,attrs:{shape:[s/a,a]}}),o=i.shape,u=new HW("real",o,t),l=new HW("imag",o,t),c=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:o},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:o}],h=n.runWebGLProgram(u,c,"float32"),p=n.runWebGLProgram(l,c,"float32"),d=Wz({inputs:{real:h,imag:p},backend:n});n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p);const f=aP({inputs:{x:d},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(d),f}const KW={kernelName:ln,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t;return qW(r,!1,n)}};class XW{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode="\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}}function YW(e){const{backend:t,attrs:n}=e,{shape:r,value:s}=n;let{dtype:a}=n;if(a=a||Oe(s),"string"===a){const e=Ie(a,le(r));return e.fill(s),t.makeTensorInfo(r,a,e)}{const e=new XW(r,s),n=[[s]];return t.runWebGLProgram(e,[],a,n)}}const JW={kernelName:cn,backendName:"webgl",kernelFunc:YW};class ZW{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n\n int coordX = ${t} - x - 1;\n float outputValue;\n if(coordX >= 0 && coordX < ${t}) {\n outputValue = getImage(coords[0], coords[1], coordX, coords[3]);\n } else {\n outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);\n }\n setOutput(outputValue);\n }\n `}}const QW={kernelName:hn,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,r=t,s=new ZW(n.shape);return r.runWebGLProgram(s,[n],n.dtype)}},eU="return floor(x);",tU=Yz({opSnippet:eU,packedOpSnippet:eU,cpuKernelImpl:yL}),nU={kernelName:pn,backendName:"webgl",kernelFunc:tU},rU=Jz({opSnippet:"\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n",packedOpSnippet:"\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n",dtype:"int32"}),sU={kernelName:dn,backendName:"webgl",kernelFunc:rU};class aU{constructor(e){this.variableNames=["A"];const t=uM(),[n,r]=e;this.outputShape=e,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}.0, ${n}.0);\n\n vec4 values = ${t.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n `}}class iU{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=uM(),[n,r]=e;this.outputShape=e,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}.0, ${n}.0);\n vec4 values = ${t.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n ${t.output} = result;\n }\n `}}const oU={kernelName:gs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e;let{pixels:s}=t;const{numChannels:a}=r,i="undefined"!=typeof HTMLVideoElement&&s instanceof HTMLVideoElement,o="undefined"!=typeof HTMLImageElement&&s instanceof HTMLImageElement,[u,l]=i?[s.videoWidth,s.videoHeight]:[s.width,s.height],c=[l,u],h=[l,u,a];if(o||i){const e=Ye().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");null!=uU&&e===lU||(lU=e,uU=document.createElement("canvas").getContext("2d",{willReadFrequently:lU})),uU.canvas.width=u,uU.canvas.height=l,uU.drawImage(s,0,0,u,l),s=uU.canvas}const p=n.makeTensorInfo(c,"int32");n.texData.get(p.dataId).usage=nD.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),s);const d=Ye().getBool("WEBGL_PACK")?new iU(h):new aU(h),f=n.runWebGLProgram(d,[p],"int32");return n.disposeData(p.dataId),f}};let uU,lU=Ye().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");const cU={kernelName:xs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:i,preluActivationWeights:o}=t,{strides:u,pad:l,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=r,m=xc(c),g=lc(s.shape,a.shape,u,h,l,p,!1,m);let y;const b=[],x=null!=i,w=null!=o,v="leakyrelu"===d,k=()=>{const e=[s,a],t=(e,t)=>{if("NCHW"===t&&1===e.shape.length&&1!==e.shape[0]){const t=aP({inputs:{x:e},backend:n,attrs:{shape:[e.shape[0],1,1]}});return b.push(t),t}return e};if(x&&e.push(t(i,c)),w&&e.push(t(o,c)),v){const t=n.makeTensorInfo([],"float32",Ys(f,"float32"));e.push(t),b.push(t)}return e};if(1!==g.filterHeight||1!==g.filterWidth||1!==g.dilationHeight||1!==g.dilationWidth||1!==g.strideHeight||1!==g.strideWidth||"SAME"!==g.padInfo.type&&"VALID"!==g.padInfo.type)if(g.strideWidth<=2&&"channelsLast"===m&&Ye().getBool("WEBGL_EXP_CONV")){const e=d?Zz(d,!0):null,t=new UB(g,x,e,w,v),r=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],s=k();y=n.runWebGLProgram(t,s,"float32",r)}else if(Ye().getBool("WEBGL_CONV_IM2COL"))y=HB({x:s,filter:a,convInfo:g,backend:n,bias:i,activation:d,preluActivationWeights:o,leakyreluAlpha:f});else{const e=d?Zz(d,!1):null,t=new BB(g,x,e,w,v),r=k();y=n.runWebGLProgram(t,r,"float32")}else y=jB({x:s,filter:a,convInfo:g,backend:n,bias:i,activation:d,preluActivationWeights:o,leakyreluAlpha:f});const I=aP({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach((e=>n.disposeIntermediateTensorInfo(e))),I}},hU={kernelName:ws,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:i,preluActivationWeights:o}=t,{strides:u,pad:l,dilations:c,dimRoundingMode:h,activation:p,leakyreluAlpha:d}=r,f=[];let m=c;null==m&&(m=[1,1]),ie(yc(u,m),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${u} and dilations '${m}'`));const g=lc(s.shape,a.shape,u,m,l,h,!0),y=Ye().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=p?Zz(p,y):null,x=[s,a],w=null!=i,v=null!=o,k="leakyrelu"===p;if(w&&x.push(i),v&&x.push(o),k){const e=n.makeTensorInfo([],"float32",Ys(d,"float32"));x.push(e),f.push(e)}let I;I=y?new vW(g,w,b,v,k):new wW(g,w,b,v,k);const N=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],S=n.runWebGLProgram(I,x,"float32",N);return f.forEach((e=>n.disposeIntermediateTensorInfo(e))),S}};class pU{constructor(e,t,n,r){this.sliceDim=e,this.strides=t,this.paramsShape=r,this.variableNames=["x","indices"],this.outputShape=n;const s=IM(n.length);let a="\n int index;";for(let e=0;e<this.sliceDim;e++)a+=`\n index = round(getIndices(coords[0], ${e}));\n out_of_bounds = out_of_bounds || index < 0;\n out_of_bounds = out_of_bounds || index >= ${this.paramsShape[e]};\n flattenIndex += index * ${this.strides[e]};`;this.userCode=`\n void main() {\n ${s} coords = getOutputCoords();\n int flattenIndex = 0;\n bool out_of_bounds = false;\n\n ${a}\n\n setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));\n }\n `}}const dU={kernelName:gn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=s.shape,i=a[a.length-1],o=le(r.shape),[u,l,c,h]=ll(r,s),p=aP({inputs:{x:s},backend:n,attrs:{shape:[l,i]}}),d=aP({inputs:{x:r},backend:n,attrs:{shape:[le(r.shape)/c,c]}});if(n.shouldExecuteOnCPU([r,s])||"string"===r.dtype){const e=n.readSync(s.dataId),t=n.bufferSync(r),a=bL(e,t,r.dtype,l,i,c,h,r.shape,o);return n.makeTensorInfo(u,r.dtype,a.values)}const f=new pU(i,h,[l,c],r.shape),m=n.runWebGLProgram(f,[d,p],d.dtype),g=aP({inputs:{x:m},backend:n,attrs:{shape:u}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(m),g}};class fU{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const n=IM(this.rank),r=function(e,t){const n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let t=0;t<e.length;t++)2===t?r.push("index"):r.push(`${n[t]}`);return r.join()}(e);this.userCode=`\n void main() {\n ${n} resRC = getOutputCoords();\n int index = int(getIndices(resRC.x, resRC.z));\n float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;\n setOutput(inBounds * getA(${r}));\n }\n `}}function mU(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:i,batchDims:o}=r,u=we(i,s.shape)[0];if(Ye().get("DEBUG")){const e=n.readSync(a.dataId),t=s.shape[u];for(let n=0;n<e.length;++n){const r=e[n];ie(r<=t-1&&r>=0,(()=>`GatherV2: the index value ${r} is not in [0, ${t-1}]`))}}const l=ug(s,a,u,o),c=le(a.shape),h=[],p=aP({inputs:{x:s},backend:n,attrs:{shape:[l.batchSize,l.outerSize,l.dimSize,l.sliceSize]}}),d=aP({inputs:{x:a},backend:n,attrs:{shape:[l.batchSize,c/l.batchSize]}});h.push(p),h.push(d);const f=[l.batchSize,l.outerSize,c/l.batchSize,l.sliceSize];if(n.shouldExecuteOnCPU([s,a])||"string"===s.dtype){const e=n.bufferSync(d),t=n.bufferSync(p),r=xL(t,e,f);return h.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(l.outputShape,r.dtype,r.values)}const m=new fU(p.shape,f),g=n.runWebGLProgram(m,[p,d],p.dtype);h.push(g);const y=aP({inputs:{x:g},backend:n,attrs:{shape:l.outputShape}});return h.forEach((e=>n.disposeIntermediateTensorInfo(e))),y}const gU={kernelName:mn,backendName:"webgl",kernelFunc:mU},yU=Jz({opSnippet:"return float(a > b);",packedOpSnippet:"\n return vec4(greaterThan(a, b));\n",cpuKernelImpl:wL,dtype:"bool"}),bU={kernelName:yn,backendName:"webgl",kernelFunc:yU},xU=Jz({opSnippet:"return float(a >= b);",packedOpSnippet:"\n return vec4(greaterThanEqual(a, b));\n",dtype:"bool",cpuKernelImpl:vL}),wU={kernelName:bn,backendName:"webgl",kernelFunc:xU},vU={kernelName:wn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t;return qW(r,!0,n)}},kU=Yz({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),IU={kernelName:kn,backendName:"webgl",kernelFunc:kU},NU=Yz({opSnippet:"return float(isinf(x));",dtype:"bool"}),SU={kernelName:In,backendName:"webgl",kernelFunc:NU},TU=Yz({opSnippet:"return float(isnan(x));",dtype:"bool"}),CU={kernelName:Nn,backendName:"webgl",kernelFunc:TU},$U=Jz({opSnippet:"return float(a < b);",packedOpSnippet:"\n return vec4(lessThan(a, b));\n",cpuKernelImpl:kL,dtype:"bool"}),EU={kernelName:Tn,backendName:"webgl",kernelFunc:$U},AU=Jz({opSnippet:"return float(a <= b);",packedOpSnippet:"\n return vec4(lessThanEqual(a, b));\n",cpuKernelImpl:IL,dtype:"bool"}),RU={kernelName:Cn,backendName:"webgl",kernelFunc:AU},OU={kernelName:$n,backendName:"webgl",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,i=NL(r,s,a);return t.makeTensorInfo([i.length],"float32",i)}},FU=Yz({opSnippet:Xz+"\n return x < 0.0 ? 0./0. : log(x);\n",packedOpSnippet:"\n vec4 result = log(x);\n bvec4 isNaN = isnan(x);\n result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);\n result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);\n result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);\n result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);\n return result;\n",cpuKernelImpl:SL}),_U={kernelName:En,backendName:"webgl",kernelFunc:FU},DU=Yz({opSnippet:Xz+"\n return log(1.0 + x);\n"}),MU={kernelName:An,backendName:"webgl",kernelFunc:DU},LU=Jz({opSnippet:"return float(a >= 1.0 && b >= 1.0);",packedOpSnippet:"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n",dtype:"bool"}),zU={kernelName:Rn,backendName:"webgl",kernelFunc:LU},PU=Yz({opSnippet:"return float(!(x >= 1.0));"}),BU={kernelName:On,backendName:"webgl",kernelFunc:PU},WU=Jz({opSnippet:"return float(a >= 1.0 || b >= 1.0);",packedOpSnippet:"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n",dtype:"bool"}),UU={kernelName:Fn,backendName:"webgl",kernelFunc:WU};class VU{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[];const a=t,i=e[3]-1;let o;this.outputShape=e;const u=`float(${n}) + float(${r}) * sum`;o=.5===s?`inversesqrt(${u})`:1===s?`1.0/(${u})`:`exp(log(${u}) * float(-${s}));`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -${a}; j <= ${a}; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= ${i}) {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * ${o};\n setOutput(val);\n }\n `}}class GU{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const a=t,i=e[3]-1;let o;this.outputShape=e;const u=`float(${n}) + float(${r}) * sum`;o=.5===s?`inversesqrt(${u})`:1===s?`1.0/(${u})`:`exp(log(${u}) * float(-${s}));`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < ${this.outputShape[3]};\n bool hasNextRow = c < ${this.outputShape[2]};\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - ${a};\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - ${a}; j <= ${a}; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i}));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * ${o};\n setOutput(result);\n }\n `}}const jU={kernelName:Ln,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:i,alpha:o,beta:u}=r,l=Ye().getBool("WEBGL_PACK_NORMALIZATION")?new GU(s.shape,a,i,o,u):new VU(s.shape,a,i,o,u);return n.runWebGLProgram(l,[s],s.dtype)}};class HU{constructor(e,t,n,r,s){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=r,this.beta=s,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < ${this.depth}; ++d) {\n int depthBegin = int(max(0.0, float(d - ${t})));\n int depthEnd = int(min(float(${this.depth}),\n float(d + ${t} + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = ${this.depth};\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float(${r}) * norm + float(${n});\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float(${r})\n * float(${s})\n * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * ${s});\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n `}}const qU={kernelName:zn,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:s,y:a,dy:i}=t,{depthRadius:o,bias:u,alpha:l,beta:c}=r,h=new HU(s.shape,o,u,l,c);return n.runWebGLProgram(h,[s,a,i],s.dtype)}};function KU(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:i}=r,o=s.shape.length,u=we(a,s.shape);let l=u;const c=xh(l,o),h=null!=c,p=n.shouldExecuteOnCPU([s]);let d=s;if(h){if(p){const e=n.texData.get(d.dataId).values,t=new Array(o);for(let e=0;e<t.length;e++)t[e]=s.shape[c[e]];const r=ez(e,s.shape,s.dtype,c,t);d=n.makeTensorInfo(t,s.dtype),n.texData.get(d.dataId).values=r}else d=pP(s,c,n);l=vh(l.length,o)}bh("max",l,o);const[f,m]=gh(d.shape,l);let g,y=f;if(i&&(y=yh(f,u)),p){const e=n.texData.get(d.dataId).values,t=TL(e,le(m),y,s.dtype);g=n.makeTensorInfo(y,s.dtype),n.texData.get(g.dataId).values=t}else g=function(e,t,n,r){const s=le(t),a=aP({inputs:{x:e},attrs:{shape:[le(e.shape)/s,s]},backend:r}),i=lP(a,e.dtype,"max",r),o=aP({inputs:{x:i},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(i),o}(d,m,y,n);return h&&n.disposeIntermediateTensorInfo(d),g}const XU={kernelName:Bn,backendName:"webgl",kernelFunc:KU},YU=Jz({opSnippet:Dz+"\n return max(a, b);\n",packedOpSnippet:"\n vec4 result = vec4(max(a, b));\n bvec4 isNaNA = isnan(a);\n bvec4 isNaNB = isnan(b);\n bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\n "+Lz+"\n return result;\n",cpuKernelImpl:CL}),JU={kernelName:Wn,backendName:"webgl",kernelFunc:YU},ZU={kernelName:Un,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t;iM(s,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:u}=r;ie(yc(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const l=oc(s.shape,a,i,1,o,u);if(1===l.filterWidth&&1===l.filterHeight&&pe(l.inShape,l.outShape))return Pz({inputs:{x:s},backend:n});const c=new JP(l,"max",!1);return n.runWebGLProgram(c,[s],s.dtype)}},QU={kernelName:Gn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:i,pad:o,dataFormat:u,dimRoundingMode:l}=r,c=uc(s.shape,a,i,[1,1,1],o,l,u),h=new ZP(c,"max",!1);return n.runWebGLProgram(h,[s],s.dtype)}};class eV{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,s=e.effectiveFilterHeight,a=e.effectiveFilterWidth,i=s-1-e.padInfo.top,o=a-1-e.padInfo.left,u=s*a-1;this.userCode=`\n const ivec2 pads = ivec2(${i}, ${o});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${s};\n wR += ${r}) {\n float dyR = float(dyRCorner + wR) / ${t}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${a}; wC++) {\n float dyC = float(dyCCorner + wC) / ${n}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = ${u} - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * ${a} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n `}}class tV{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,u=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=o-1-e.padInfo.front,h=u-1-e.padInfo.top,p=l-1-e.padInfo.left,d=o*u*l-1;this.userCode=`\n const ivec3 pads = ivec3(${c}, ${h}, ${p});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < ${o};\n wD += ${s}) {\n float dyD = float(dyDCorner + wD) / ${t}.0;\n\n if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${u};\n wR += ${a}) {\n float dyR = float(dyRCorner + wR) / ${n}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${l};\n wC += ${i}) {\n float dyC = float(dyCCorner + wC) / ${r}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = ${d} -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * ${u} * ${l} +\n wR * ${l} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const nV={kernelName:jn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,i=a,{filterSize:o,strides:u,pad:l,dimRoundingMode:c}=r,h=uc(i.shape,o,u,[1,1,1],l,c),p=new ZP(h,"max",!0),d=n.runWebGLProgram(p,[i],i.dtype),f=new tV(h),m=n.runWebGLProgram(f,[s,d],i.dtype);return n.disposeIntermediateTensorInfo(d),m}},rV={kernelName:Vn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:i}=t,o=a;iM([a,i],"maxPoolGrad");const{filterSize:u,strides:l,pad:c,dimRoundingMode:h}=r,p=oc(o.shape,u,l,1,c,h),d=new JP(p,"max",!0),f=n.runWebGLProgram(d,[o],o.dtype),m=new eV(p),g=n.runWebGLProgram(m,[s,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}},sV={kernelName:Hn,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{filterSize:s,strides:a,pad:i,includeBatchInIndex:o}=t,u=n;ie(4===r.shape.length,(()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`));const l=[1,1];ie(yc(a,l),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${l}'`));const c=oc(r.shape,s,a,l,i),[h,p]=function(e,t,n,r){let s=new JP(n,"max",!1);const a=r.runWebGLProgram(s,[e],"float32");return s=new JP(n,"max",!0,!0,t),[a,r.runWebGLProgram(s,[e],"float32")]}(r,o,c,u);return[h,p]}},aV={kernelName:qn,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{keepDims:s,axis:a}=t,i=n,o=r.shape.length,u=we(a,r.shape);let l=u;const c=xh(l,o),h=null!=c,p=i.shouldExecuteOnCPU([r]),d=[];let f=r;if(h){if(p){const e=i.texData.get(f.dataId).values,t=new Array(o);for(let e=0;e<t.length;e++)t[e]=r.shape[c[e]];const n=ez(e,r.shape,r.dtype,c,t);f=i.makeTensorInfo(t,r.dtype),i.texData.get(f.dataId).values=n}else f=pP(r,c,i);d.push(f),l=vh(l.length,o)}bh("sum",l,o);const[m,g]=gh(f.shape,l);let y=m;s&&(y=yh(m,u));const b=function(e,t,n,r){const s=le(t),a=aP({inputs:{x:e},attrs:{shape:[le(e.shape)/s,s]},backend:r}),i=lP(a,"float32","mean",r),o=aP({inputs:{x:i},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(i),o}(f,g,y,i);for(const e of d)i.disposeIntermediateTensorInfo(e);return b}},iV={kernelName:Kn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r,o=s.shape.length,u=we(a,s.shape);let l=u;const c=xh(l,o);let h=s;null!=c&&(h=mP({inputs:{x:s},backend:n,attrs:{perm:c}}),l=vh(l.length,s.shape.length)),bh("min",l,o);const[p,d]=gh(h.shape,l),f=aP({inputs:{x:h},backend:n,attrs:{shape:[-1,le(d)]}}),m=lP(f,f.dtype,"min",n);let g;return g=aP(i?{inputs:{x:m},backend:n,attrs:{shape:yh(p,u)}}:{inputs:{x:m},backend:n,attrs:{shape:p}}),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}},oV=Jz({opSnippet:Dz+"\n return min(a, b);\n",packedOpSnippet:"\n vec4 result = vec4(min(a, b));\n bvec4 isNaNA = isnan(a);\n bvec4 isNaNB = isnan(b);\n bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\n "+Lz+"\n return result;\n",cpuKernelImpl:$L}),uV={kernelName:Xn,backendName:"webgl",kernelFunc:oV};class lV{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length,s=IM(r),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),u="reflect"===n?0:1;this.userCode=1!==r?`\n ${s} start = ${s}(${a});\n ${s} end = ${s}(${i});\n\n void main() {\n ${s} outC = getOutputCoords();\n for (int i = 0; i < ${r}; i++) {\n if (outC[i] < start[i]) {\n outC[i] = start[i] * 2 - outC[i] - ${u};\n } else if(outC[i] >= end[i]) {\n outC[i] = (end[i] - 1) * 2 - outC[i] + ${u};\n }\n }\n ${s} coords = outC - start;\n setOutput(getX(${o}));\n }\n `:`\n int start = ${a};\n int end = ${i};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start) {\n outC = start * 2 - outC - ${u};\n } else if(outC >= end) {\n outC = (end - 1) * 2 - outC + ${u};\n }\n setOutput(getX(outC - start));\n }\n `}}class cV{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length,s=IM(r),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=rz("rc",r),u=rz("source",r),l=`${o[r-1]} < ${this.outputShape[r-1]}`,c=1===r?"source":`vec2(${u.slice(-2).join()})`,h="reflect"===n?0:1;let p="";if(1===r){const e=`\n ${s} source = rc;\n if (source < start) {\n source = start * 2 - source - ${h};\n } else if (source >= end) {\n source = (end - 1) * 2 - source + ${h};\n }\n source -= start;\n `;p=`\n ${s} rc = outputLoc;\n ${e}\n result[0] = getChannel(getX(${u.join()}), ${c});\n ${o[r-1]} += 1;\n if(${l}) {\n ${e}\n result[1] = getChannel(getX(${u.join()}), ${c});\n }\n `}else{const e=`\n ${s} source = rc;\n ${s} lt = ${s}(lessThan(source, start));\n ${s} gte = ${s}(greaterThanEqual(source, end));\n ${s} orig = 1 - (lt + gte);\n source = orig * source +\n lt * (start * 2 - source - ${h}) +\n gte * ((end - 1) * 2 - source + ${h});\n source -= start;\n `;p=`\n ${s} rc = outputLoc;\n ${e}\n result[0] = getChannel(getX(${u.join()}), ${c});\n ${o[r-1]} += 1;\n if(${l}) {\n ${e}\n result[1] = getChannel(getX(${u.join()}), ${c});\n }\n rc = outputLoc;\n ${o[r-2]} += 1;\n if(${o[r-2]} < ${this.outputShape[r-2]}) {\n ${e}\n result[2] = getChannel(getX(${u.join()}), ${c});\n ${o[r-1]} += 1;\n if(${l}) {\n ${e}\n result[3] = getChannel(getX(${u.join()}), ${c});\n }\n }\n `}this.userCode=`\n const ${s} start = ${s}(${a});\n const ${s} end = ${s}(${i});\n\n void main() {\n ${s} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${p}\n setOutput(result);\n }\n `}}const hV={kernelName:Yn,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r}=e,{paddings:s,mode:a}=n,i=Ye().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new cV(r.shape,s,a):new lV(r.shape,s,a);return t.runWebGLProgram(i,[r],r.dtype)}},pV=Jz({opSnippet:"if (b == 0.0) return NAN;\n return mod(a, b);",packedOpSnippet:"\n vec4 result = mod(a, b);\n bvec4 isNaN = equal(b, vec4(0.0));\n "+Lz+"\n return result;\n"}),dV={kernelName:Jn,backendName:"webgl",kernelFunc:pV};class fV{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < ${t-1}; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float(${t-1}));\n }\n `}}const mV=Jz({opSnippet:"\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",packedOpSnippet:"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n",checkOutOfBounds:!0}),gV={kernelName:Qt,backendName:"webgl",kernelFunc:mV},yV="return a - b;",bV=Jz({opSnippet:yV,packedOpSnippet:yV,supportsComplex:!0,cpuKernelImpl:JL}),xV={kernelName:rs,backendName:"webgl",kernelFunc:bV};function wV(e){const{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,i=we([a],s.shape),o=KU({inputs:{x:s},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),u=yh(o.shape,i),l=aP({inputs:{x:o},backend:n,attrs:{shape:u}}),c=bV({inputs:{a:s,b:l},backend:n}),h=PW({inputs:{x:c},backend:n}),p=dP({inputs:{x:h},backend:n,attrs:{axis:i,keepDims:!1}}),d=aP({inputs:{x:p},backend:n,attrs:{shape:u}}),f=mV({inputs:{a:h,b:d},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),f}const vV={kernelName:Gr,backendName:"webgl",kernelFunc:wV},kV={kernelName:Zn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:i,normalized:o}=r,u=o?s:wV({inputs:{logits:s},backend:n,attrs:{dim:s.shape.length-1}}),l=u.shape[0],c=u.shape[1],h=new fV(l,c,a),p=[[i]],d=n.runWebGLProgram(h,[u],"int32",p);return o||n.disposeIntermediateTensorInfo(u),d}},IV=pz+"\n return -x;\n",NV={kernelName:er,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){const e=n.texData.get(r.dataId),[t,s]=AL(e.values,r.shape,r.dtype);return n.makeTensorInfo(s,r.dtype,t)}let s;return s=Ye().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new Sz(r.shape,"\n vec4 result = -x;\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"):new hz(r.shape,IV),n.runWebGLProgram(s,[r],r.dtype)}},SV=mf,TV={kernelName:nr,backendName:"webgl",kernelFunc:function(e){ks("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u}=r,l=n.readSync(s.dataId),c=n.readSync(a.dataId),{selectedIndices:h}=SV(l,c,i,o,u);return n.makeTensorInfo([h.length],"int32",new Int32Array(h))}},CV=gf,$V={kernelName:rr,backendName:"webgl",kernelFunc:function(e){ks("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u,padToMaxOutputSize:l}=r,c=n.readSync(s.dataId),h=n.readSync(a.dataId),{selectedIndices:p,validOutputs:d}=CV(c,h,i,o,u,l);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([d]))]}},EV=yf,AV={kernelName:sr,backendName:"webgl",kernelFunc:function(e){ks("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u,softNmsSigma:l}=r,c=n.readSync(s.dataId),h=n.readSync(a.dataId),p=i,d=o,f=u,m=l,{selectedIndices:g,selectedScores:y}=EV(c,h,p,d,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};class RV{constructor(e,t,n,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float(${r}), float(${n}),\n float(index == coords.y)));\n }\n `}}const OV={kernelName:ir,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{dtype:a,depth:i,onValue:o,offValue:u}=r,l=le(s.shape),c=new RV(l,i,o,u),h=aP({inputs:{x:s},backend:n,attrs:{shape:[l]}}),p=n.runWebGLProgram(c,[h],a);n.disposeIntermediateTensorInfo(h);const d=aP({inputs:{x:p},backend:n,attrs:{shape:[...s.shape,i]}});return n.disposeIntermediateTensorInfo(p),d}};function FV(e){const{inputs:t,backend:n}=e,{x:r}=t;if("complex64"===r.dtype){const e=wB({inputs:{input:r},backend:n}),t=FV({inputs:{x:e},backend:n}),s=DB({inputs:{input:r},backend:n}),a=FV({inputs:{x:s},backend:n}),i=Wz({inputs:{real:t,imag:a},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),i}return YW({attrs:{shape:r.shape,dtype:r.dtype,value:"string"===r.dtype?"":0},backend:n})}const _V={kernelName:fs,backendName:"webgl",kernelFunc:FV},DV={kernelName:ar,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r}=t,{x:s}=n;if("string"===s.dtype)throw new Error("onesLike is not supported under string dtype");if("complex64"===s.dtype){const t=wB({inputs:{input:s},backend:r}),n=e({inputs:{x:t},backend:r}),a=DB({inputs:{input:s},backend:r}),i=FV({inputs:{x:a},backend:r}),o=Wz({inputs:{real:n,imag:i},backend:r});return r.disposeIntermediateTensorInfo(t),r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(i),o}return YW({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:r})}},MV={kernelName:or,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(1===t.length)return WW({inputs:{input:t[0]},backend:n,attrs:{dim:s}});const a=t[0].shape,i=t[0].dtype;t.forEach((e=>{oe(a,e.shape,"All tensors passed to stack must have matching shapes"),ie(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],u=zB({inputs:t.map((e=>{const t=WW({inputs:{input:e},backend:n,attrs:{dim:s}});return o.push(t),t})),backend:n,attrs:{axis:s}});return o.forEach((e=>n.disposeIntermediateTensorInfo(e))),u}};class LV{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length,s=IM(r),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?`\n ${s} start = ${s}(${a});\n ${s} end = ${s}(${i});\n\n void main() {\n ${s} outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(value);\n } else {\n ${s} coords = outC - start;\n setOutput(getX(${o}));\n }\n }\n `:`\n int start = ${a};\n int end = ${i};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(value);\n } else {\n setOutput(getX(outC - start));\n }\n }\n `}}class zV{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length,s=IM(r),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=rz("rc",r),u=rz("source",r),l=`${o[r-1]} < ${this.outputShape[r-1]}`,c=1===r?"source":`vec2(${u.slice(-2).join()})`,h=[`${s} rc = outputLoc;`,`${o[r-1]} += 1;\n if(${l}) {\n `,1===r?"":`}\n rc = outputLoc;\n ${o[r-2]} += 1;\n if(${o[r-2]} < ${this.outputShape[r-2]}) {`,1===r?"":` ${o[r-1]} += 1;\n if(${l}) {`],p=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let d="";for(let e=0,t=1===r?2:4;e<t;e++)d+=`\n ${h[e]}\n if (${p}) {\n result[${e}] = float(value);\n } else {\n ${s} source = rc - start;\n result[${e}] = getChannel(getX(${u.join()}), ${c});\n }\n `;d+=1===r?"} ":"}}",this.userCode=`\n const ${s} start = ${s}(${a});\n const ${s} end = ${s}(${i});\n\n void main() {\n ${s} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${d}\n setOutput(result);\n }\n `}}const PV=e=>{const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:i}=r;if(0===le(s.shape)){const e=a.map(((e,t)=>e[0]+s.shape[t]+e[1]));return YW({backend:n,attrs:{shape:e,value:i,dtype:s.dtype}})}const o=Ye().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new zV(s.shape,a,i):new LV(s.shape,a,i),u=[[i]];return n.runWebGLProgram(o,[s],s.dtype,u)},BV={kernelName:ur,backendName:"webgl",kernelFunc:PV},WV=Jz({opSnippet:"\n if(a < 0.0 && floor(b) < b){\n return NAN;\n }\n if (b == 0.0) {\n return 1.0;\n }\n return (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",packedOpSnippet:"\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n bvec4 isNaN1 = lessThan(a, vec4(0.0));\n bvec4 isNaN2 = lessThan(floor(b), b);\n bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);\n "+Lz+"\n return result;\n"}),UV={kernelName:cr,backendName:"webgl",kernelFunc:WV},VV={kernelName:pr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:i}=r,o=s.shape.length,u=[],l=we(a,s.shape);let c=l;const h=xh(c,o);let p,d=s;if(null!=h&&(d=mP({inputs:{x:s},backend:n,attrs:{perm:h}}),c=vh(c.length,o),u.push(d)),bh("prod",c,o),n.shouldExecuteOnCPU([d])){const e=n.texData.get(d.dataId).values,{outVals:t,outShape:r,outDtype:s}=OL(d.shape,d.dtype,e,c);p=n.makeTensorInfo(r,s,t)}else{const[e,t]=gh(d.shape,c),r=le(t),a=aP({inputs:{x:d},backend:n,attrs:{shape:[-1,r]}}),i=lP(a,Aa(s.dtype),"prod",n);p=aP({inputs:{x:i},backend:n,attrs:{shape:e}}),u.push(a),u.push(i)}if(i){u.push(p);const e=yh(p.shape,l);p=aP({inputs:{x:p},backend:n,attrs:{shape:e}})}return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),p}},GV={kernelName:dr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{paramsNestedSplits:s,paramsDenseValues:a,indices:i}=t,{outputRaggedRank:o}=r,u=s.map((e=>n.readSync(e.dataId))),l=s.map((e=>e.shape)),c=n.readSync(a.dataId),h=n.readSync(i.dataId),[p,d,f]=FL(u,l,c,a.shape,a.dtype,h,i.shape,o),m=p.map((e=>n.makeTensorInfo([e.length],"int32",e))),g=n.makeTensorInfo(f,a.dtype,d);return m.concat([g])}},jV={kernelName:fr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{starts:r,limits:s,deltas:a}=t,i=n.readSync(r.dataId),o=n.readSync(s.dataId),u=n.readSync(a.dataId),[l,c]=_L(i,r.shape,r.dtype,o,s.shape,u,a.shape);return[n.makeTensorInfo([l.length],"int32",l),n.makeTensorInfo([c.length],r.dtype,c)]}},HV={kernelName:mr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{shape:s,values:a,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:u}=r,l=n.readSync(s.dataId),c=n.readSync(a.dataId),h=n.readSync(i.dataId),p=o.map((e=>n.readSync(e.dataId))),d=o.map((e=>e.shape)),[f,m]=DL(l,s.shape,c,a.shape,a.dtype,h,i.shape,p,d,u);return n.makeTensorInfo(f,a.dtype,m)}},qV=e=>{const{backend:t,attrs:n}=e,{start:r,stop:s,step:a,dtype:i}=n,o=ML(r,s,a,i);return t.makeTensorInfo([o.length],i,o)},KV={kernelName:gr,backendName:"webgl",kernelFunc:qV},XV=Yz({opSnippet:"return 1.0 / x;"}),YV={kernelName:br,backendName:"webgl",kernelFunc:XV},JV=Yz({opSnippet:pz+"\n return (x < 0.0) ? 0.0 : x;\n",packedOpSnippet:"\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"}),ZV={kernelName:xr,backendName:"webgl",kernelFunc:JV},QV=Yz({opSnippet:pz+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",packedOpSnippet:"\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"}),eG={kernelName:Sr,backendName:"webgl",kernelFunc:QV};class tG{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];const[a,i,o,u]=e;this.outputShape=[a,t,n,u];const l=[r&&t>1?i-1:i,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];let h;h=s?"(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${l[0]/c[0]},\n ${l[1]/c[1]});\n const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${h};\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n `}}class nG{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[a,i,o,u]=e;this.outputShape=[a,t,n,u];const l=[r&&t>1?i-1:i,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];let h;h=s?"(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${l[0]/c[0]},\n ${l[1]/c[1]},\n ${l[1]/c[1]});\n const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,\n ${o}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${h};\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${u-1};\n bool hasNextRow = coords.z < ${n-1};\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n `}}const rG={kernelName:Ir,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:i,size:o}=r,[u,l]=o,c=Ye().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new nG(s.shape,u,l,a,i):new tG(s.shape,u,l,a,i);return n.runWebGLProgram(c,[s],"float32")}};class sG{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,s]=t,[,a,i]=e,o=[n&&a>1?r-1:r,n&&i>1?s-1:s],u=[n&&a>1?a-1:a,n&&i>1?i-1:i],l=o[0]/u[0],c=o[1]/u[1],h=1/l,p=1/c,d=2*Math.ceil(h)+2,f=2*Math.ceil(p)+2;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(${l});\n const float widthScale = float(${c});\n\n const float invHeightScale = float(${h});\n const float invWidthScale = float(${p});\n\n const int winHeight = int(${d});\n const int winWidth = int(${f});\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= ${a}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${i}) {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), ${r-1}.0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), ${s-1}.0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n `}}const aG={kernelName:Nr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:i}=r,o=new sG(a.shape,s.shape,i);return n.runWebGLProgram(o,[a],a.dtype)}};class iG{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];const[a,i,o,u]=e;this.outputShape=[a,t,n,u];const l=[r&&t>1?i-1:i,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n],h=r?"0.5":"0.0";let p;p=s?"max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${l[0]/c[0]},\n ${l[1]/c[1]});\n const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${p};\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n `}}class oG{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[a,i,o,u]=e;this.outputShape=[a,t,n,u];const l=[r&&t>1?i-1:i,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n],h=r?"0.5":"0.0";let p;p=s?"max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${l[0]/c[0]},\n ${l[1]/c[1]},\n ${l[1]/c[1]});\n const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,\n ${o}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${p};\n\n // Compute the coordinators of nearest neighbor point.\n ivec3 sourceNearestRC = ivec3(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${u-1};\n bool hasNextRow = coords.z < ${n-1};\n\n vec4 newValue = vec4(\n getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),\n hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);\n\n setOutput(newValue);\n }\n `}}const uG={kernelName:vr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:i,size:o}=r,[u,l]=o,c=Ye().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new oG(s.shape,u,l,a,i):new iG(s.shape,u,l,a,i);return n.runWebGLProgram(c,[s],s.dtype)}};class lG{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,s]=t,[,a,i]=e,o=[n&&a>1?r-1:r,n&&i>1?s-1:s],u=[n&&a>1?a-1:a,n&&i>1?i-1:i],l=o[0]/u[0],c=o[1]/u[1],h=1/l,p=1/c,d=2*Math.ceil(h)+2,f=2*Math.ceil(p)+2;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(${l});\n const float widthScale = float(${c});\n\n const float invHeightScale = float(${h});\n const float invWidthScale = float(${p});\n\n const int winHeight = int(${d});\n const int winWidth = int(${f});\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= ${a}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${i}) {\n continue;\n }\n\n float sourceFracRow =\n float(${o[0]}) *\n (float(dyR) / float(${u[0]}));\n\n float sourceFracCol =\n float(${o[1]}) *\n (float(dyC) / float(${u[1]}));\n\n int sourceNearestRow = int(min(\n float(int(${r}) - 1),\n ${n} ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int(${s}) - 1),\n ${n} ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n `}}const cG={kernelName:kr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:i}=r,o=new lG(a.shape,s.shape,i);return n.runWebGLProgram(o,[a],a.dtype)}};class hG{constructor(e,t){this.variableNames=["x"];const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,1===n)return void(this.userCode=`\n void main() {\n int coord = getOutputCoords();\n setOutput(getX(${e[0]} - coord - 1));\n }\n `);const r=e.map(((n,r)=>(n=>-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - coords[${n}] - 1`:`coords[${n}]`)(r))).join(","),s=IM(n);this.userCode=`\n void main() {\n ${s} coords = getOutputCoords();\n setOutput(getX(${r}));\n }\n `}}class pG{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const r=rz("rc",n),s=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,i=IM(n);function o(n){const r=e.map(((r,s)=>function(n,r){return-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - ${r[n]} - 1`:`${r[n]}`}(s,n)));return`getChannel(getX(${r.join(",")}), vec2(${r.slice(-2).join(",")}))`}this.userCode=1===n?`\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX(${e[0]} - rc - 1),\n ${e[0]} - rc - 1);\n if(${s}){\n result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),\n ${e[0]} - (rc + 1) - 1);\n }\n setOutput(result);\n }\n `:`\n void main() {\n ${i} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = ${function(e){return o(e)}(r.slice())};\n if(${s}){\n result.g = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",o(e)}(r.slice())};\n }\n if(${a}) {\n result.b = ${function(e){return e[n-2]="("+e[n-2]+" + 1)",o(e)}(r.slice())};\n if(${s}) {\n result.a = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",e[n-2]="("+e[n-2]+" + 1)",o(e)}(r.slice())};\n }\n }\n setOutput(result);\n }\n `}}const dG={kernelName:Tr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r,i=s.shape.length,o=we(a,s.shape);if(0===i)return Pz({inputs:{x:s},backend:n});const u=Ye().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new pG(s.shape,o):new hG(s.shape,o);return n.runWebGLProgram(u,[s],s.dtype)}};class fG{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];const n=e[1],r=e[2];this.outputShape=e;let s="";s="number"==typeof t?`float outputValue = ${t.toFixed(2)};`:`\n vec3 fill = vec3(${t.join(",")});\n float outputValue = fill[coords[3]];`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n int y = coords[1];\n float coordXFloat = (float(x) - params[0]) * params[3] -\n (float(y) - params[1]) * params[2];\n float coordYFloat = (float(x) - params[0]) * params[2] +\n (float(y) - params[1]) * params[3];\n int coordX = int(round(coordXFloat + params[0]));\n int coordY = int(round(coordYFloat + params[1]));\n ${s}\n if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${n}) {\n outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n }\n setOutput(outputValue);\n }\n `}}const mG={kernelName:ys,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,{radians:s,fillValue:a,center:i}=t,o=n,u=new fG(r.shape,a),[l,c]=mm(i,r.shape[1],r.shape[2]),h=[[l,c,Math.sin(s),Math.cos(s)]];return o.runWebGLProgram(u,[r],r.dtype,h)}},gG=Yz({opSnippet:"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n"}),yG={kernelName:Cr,backendName:"webgl",kernelFunc:gG},bG=Yz({opSnippet:"return inversesqrt(x);",cpuKernelImpl:LL}),xG={kernelName:$r,backendName:"webgl",kernelFunc:bG};class wG{constructor(e,t,n,r,s,a,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;const u=IM(s.length),l=IM(a.length);let c="";1===n?c="i":2===n&&(c="i, j");const h=`getIndices(${c})`;let p="";1===r?p="i":2===r&&(p="i, coords[1]");const d=`getUpdates(${p})`;let f="";o&&(f="coords[0], coords[1]");const m=`getDefaultValue(${f})`,g=t>1?"strides[j]":"strides";this.userCode=`\n ${u} strides = ${u}(${s});\n\n void main() {\n ${l} coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < ${e}; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < ${t}; j++) {\n int index = round(${h});\n flattenedIndex += index * ${g};\n }\n if (flattenedIndex == coords[0]) {\n sum += ${d};\n found = true;\n }\n }\n setOutput(mix(${m}, sum, float(found)));\n }\n `}}class vG{constructor(e,t,n,r,s,a,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=a;const u=IM(s.length),l=IM(a.length);let c="";1===n?c="i":2===n&&(c="i, j");const h=`getIndices(${c})`;let p="";1===r?p="i":2===r&&(p="i, coords[1]");const d=`getUpdates(${p})`;let f="";o&&(f="coords[0], coords[1]");const m=`getDefaultValue(${f})`,g=t>1?"strides[j]":"strides",y=t>1?"strides[j + 1]":"strides";this.userCode=`\n ${u} strides = ${u}(${s});\n\n void main() {\n ${l} coords = getOutputCoords();\n vec4 sum = vec4(0.);\n vec4 found = vec4(0.);\n for (int i = 0; i < ${e}; i+=2) {\n ivec2 flattenedIndex = ivec2(0);\n for (int j = 0; j < ${t}; j+=2) {\n ivec4 index = round(${h});\n flattenedIndex += index.xz * ${g};\n if (j + 1 < ${t}) {\n flattenedIndex += index.yw * ${y};\n }\n }\n if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||\n flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {\n vec4 updVals = ${d};\n if (flattenedIndex[0] == coords[0]) {\n sum.xy += updVals.xy;\n found.xy = vec2(1.);\n } else if (flattenedIndex[0] == coords[0] + 1) {\n sum.zw += updVals.xy;\n found.zw = vec2(1.);\n }\n if (flattenedIndex[1] == coords[0]) {\n sum.xy += updVals.zw;\n found.xy = vec2(1.);\n } else if (flattenedIndex[1] == coords[0] + 1) {\n sum.zw += updVals.zw;\n found.zw = vec2(1.);\n }\n }\n }\n setOutput(mix(${m}, sum, found));\n }\n `}}const kG={kernelName:Er,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:i}=r,{sliceRank:o,numUpdates:u,sliceSize:l,strides:c,outputSize:h}=pl(0,s,i),p=[h/l,l];if(0===h)return n.makeTensorInfo(i,s.dtype);const d=aP({inputs:{x:s},backend:n,attrs:{shape:[u,o]}}),f=aP({inputs:{x:a},backend:n,attrs:{shape:[u,l]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0]));let g;g=Ye().getBool("WEBGL_PACK")?new vG(u,o,d.shape.length,f.shape.length,c,p):new wG(u,o,d.shape.length,f.shape.length,c,p);const y=n.runWebGLProgram(g,[f,d,m],f.dtype),b=aP({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(m),b}};class IG{constructor(e,t,n,r){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,n];const s=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,a=2===Ye().getNumber("WEBGL_VERSION")?"while (left < right) {":s,i="left"===r?"<":"<=";this.userCode=`\n int findBound(int batch, float value) {\n int left = 0;\n int right = numInputs;\n int mid;\n ${a}\n mid = (left + right) / 2;\n if (getSortedSequence(batch, mid) ${i} value) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n return right;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int valueIndex = coords[1];\n\n float value = getValues(batch, valueIndex);\n\n setOutput(float(findBound(batch, value)));\n }\n `}}const NG={kernelName:Rr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sortedSequence:s,values:a}=t,{side:i}=r,o=new IG(s.shape[0],s.shape[1],a.shape[1],i),u=[[s.shape[1]]];return n.runWebGLProgram(o,[s,a],"int32",u)}};class SG{constructor(e,t,n){let r,s;if(this.variableNames=["c","a","b"],this.outputShape=t,n>4)throw Error(`Where for rank ${n} is not yet supported`);if(1===n)s="resRC",r="resRC";else{const n=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],i=[];for(let r=0;r<t.length;r++)i.push(`${n[r]}`),r<e&&a.push(`${n[r]}`);r=a.join(),s=i.join()}const a=IM(n);this.userCode=`\n void main() {\n ${a} resRC = getOutputCoords();\n float cVal = getC(${r});\n if (cVal >= 1.0) {\n setOutput(getA(${s}));\n } else {\n setOutput(getB(${s}));\n }\n }\n `}}const TG={kernelName:Or,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t,i=new SG(r.shape.length,s.shape,s.shape.length);return n.runWebGLProgram(i,[r,s,a],Ea(s.dtype,a.dtype))}},CG=Yz({opSnippet:`\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = ${vm};\n float scale = ${km};\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n`}),$G={kernelName:Fr,backendName:"webgl",kernelFunc:CG},EG=Yz({opSnippet:Xz+"\n return 1.0 / (1.0 + exp(-1.0 * x));\n",packedOpSnippet:"\n vec4 result = 1.0 / (1.0 + exp(-1.0 * x));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",cpuKernelImpl:PL}),AG={kernelName:zr,backendName:"webgl",kernelFunc:EG},RG=Yz({opSnippet:"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n"}),OG={kernelName:Lr,backendName:"webgl",kernelFunc:RG},FG=Yz({opSnippet:Xz+"\n return sin(x);\n",packedOpSnippet:`\n vec4 result = sin(x);\n bvec4 isNaN = isnan(x);\n ${Lz}\n return result;\n`}),_G={kernelName:Dr,backendName:"webgl",kernelFunc:FG},DG=Yz({opSnippet:"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n"}),MG={kernelName:Mr,backendName:"webgl",kernelFunc:DG},LG=Yz({opSnippet:"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n"}),zG={kernelName:Pr,backendName:"webgl",kernelFunc:LG},PG={kernelName:Ur,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:i}=r;ie(s.shape.length<=4,(()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"));const o=a.reduce(((e,t)=>e*t)),u=[[0,0]];u.push(...i);for(let e=1+a.length;e<s.shape.length;++e)u.push([0,0]);const l=[],c=PV({inputs:{x:s},backend:n,attrs:{paddings:u,constantValue:0}}),h=gm(c.shape,a,o,!1),p=ym(h.length,a.length,!1),d=bm(c.shape,a,o,!1),f=aP({inputs:{x:c},backend:n,attrs:{shape:h}}),m=mP({inputs:{x:f},backend:n,attrs:{perm:p}}),g=aP({inputs:{x:m},backend:n,attrs:{shape:d}});return l.push(c),l.push(f),l.push(m),l.forEach((e=>n.disposeIntermediateTensorInfo(e))),g}},BG={kernelName:jr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{indices:r,values:s,denseShape:a,defaultValue:i}=t;if(1!==a.shape.length)throw new Error(`Dense shape must be a vector, saw:\n ${a.shape}`);if(2!==r.shape.length)throw new Error(`Indices must be a matrix, saw:\n ${r.shape}`);if(1!==s.shape.length)throw new Error(`Values must be a vector, saw:\n ${s.shape}`);if(0!==i.shape.length)throw new Error(`Default value must be a scalar, saw:\n ${i.shape}`);const o=n.readSync(r.dataId),u=n.readSync(s.dataId),l=n.readSync(a.dataId),c=n.readSync(i.dataId)[0],[h,p,d,f,m]=UL(o,r.shape,r.dtype,u,s.dtype,l,c);return[n.makeTensorInfo(p,r.dtype,h),n.makeTensorInfo([p[0]],s.dtype,d),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map((e=>Number(e))))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}},WG={kernelName:Hr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(2!==r.shape.length)throw new Error(`Input indices should be a matrix but received shape ${r.shape}`);if(1!==s.shape.length)throw new Error(`Input shape should be a vector but received shape ${s.shape}`);if(1!==a.shape.length)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);const i=Array.from(n.readSync(s.dataId)),o=n.readSync(r.dataId),u=Array.from(n.readSync(a.dataId)),[l,c,h]=VL(o,r.shape,r.dtype,i,u);return[n.makeTensorInfo(c,r.dtype,l),n.makeTensorInfo([h.length],a.dtype,new Int32Array(h))]}},UG={kernelName:qr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.shape.length)throw new Error(`Indices should be a vector but received shape\n ${s.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${a.shape}`);const i=n.readSync(r.dataId),o=n.readSync(s.dataId),u=n.readSync(a.dataId),[l,c]=GL(i,r.shape,r.dtype,o,u,!0);return n.makeTensorInfo(c,r.dtype,l)}},VG={kernelName:Kr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.shape.length)throw new Error(`Indices should be a vector but received shape\n ${s.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${a.shape}`);const i=n.readSync(r.dataId),o=n.readSync(s.dataId),u=n.readSync(a.dataId),[l,c]=GL(i,r.shape,r.dtype,o,u);return n.makeTensorInfo(c,r.dtype,l)}},GG={kernelName:Xr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:i}=t,{outputShape:o}=r,{sliceRank:u,numUpdates:l,sliceSize:c,strides:h,outputSize:p}=pl(0,s,o);if("string"===a.dtype){const e=n.bufferSync(s),t=n.bufferSync(a),r=ta(n.readSync(i.dataId)[0]),d=zL(e,t,o,p,c,l,u,h,r,!1);return n.makeTensorInfo(o,d.dtype,d.values)}const d=new wG(l,u,s.shape.length,a.shape.length,h,[p,1],!1),f=n.runWebGLProgram(d,[a,s,i],a.dtype),m=aP({inputs:{x:f},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(f),m}},jG={kernelName:Vr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:i}=r,o=we(i,s.shape)[0],u=qm(s,a,o),l=s.shape.length,c=new Array(l).fill(0),h=s.shape.slice();return u.map((e=>{const t=[...h];t[o]=e;const r=pB({inputs:{x:s},backend:n,attrs:{begin:c,size:t}});return c[o]+=e,r}))}},HG="return sqrt(x);",qG=Yz({opSnippet:HG,packedOpSnippet:HG,cpuKernelImpl:jL}),KG={kernelName:Br,backendName:"webgl",kernelFunc:qG},XG=Yz({opSnippet:"return x * x;"}),YG={kernelName:Jr,backendName:"webgl",kernelFunc:XG},JG="return (a - b) * (a - b);",ZG=Jz({opSnippet:JG,packedOpSnippet:JG}),QG={kernelName:Yr,backendName:"webgl",kernelFunc:ZG},ej={kernelName:Zr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t;if("string"!==s.dtype)throw new Error("Input must be of datatype string");const a=lg(n.readSync(s.dataId)),i=HL(a,"string",r);return n.makeTensorInfo(s.shape,"string",i)}},tj={kernelName:ms,backendName:"webgl",kernelFunc:function({inputs:e,attrs:t,backend:n}){const{x:r}=e,s=pz+`\n return x > 0.0 ? 1.0 : float(${t.alpha});\n `,a=new hz(r.shape,s);return n.runWebGLProgram(a,[r],r.dtype)}};class nj{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const r=n.length,s=IM(n.length),a=IM(n.length);let i="";if(1===r)i="coords * strides + begin";else{let e=0;i=n.map(((t,r)=>(e++,1===n.length?`coords * strides[${r}] + begin[${r}]`:`coords[${e-1}] * strides[${r}] + begin[${r}]`))).join(",")}this.userCode=`\n ${s} begin = ${s}(${e});\n ${s} strides = ${s}(${t});\n\n void main() {\n ${a} coords = getOutputCoords();\n setOutput(getX(${i}));\n }\n `}}const rj={kernelName:Qr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:i,strides:o,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:h,shrinkAxisMask:p}=r,{finalShapeSparse:d,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:w}=Al(s.shape,a,i,o,u,l,c,h,p);let v;if(m)v=aP({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||y){ie(s.shape.length>=1,(()=>`Input must have rank at least 1, got: ${s.shape.length}`));const e=yl(b,x,w),t=pB({inputs:{x:s},backend:n,attrs:{begin:b,size:e}});v=aP({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else if(n.shouldExecuteOnCPU([s])){const e=n.readSync(s.dataId),t=Mo(s.shape,s.dtype,e),r=qL(d,t,w,b);v=n.makeTensorInfo(f,s.dtype,r.values)}else{const e=new nj(b,w,d);v=n.runWebGLProgram(e,[s],s.dtype)}const k=aP({inputs:{x:v},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(v),k}},sj={kernelName:es,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:i,rightPad:o,padWidth:u,preserveShortSequences:l}=r,{data:c,dataSplits:h}=t,p=n.readSync(c.dataId),d=n.readSync(h.dataId),[f,m]=KL(p,d,s,a,i,o,u,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(h.shape,"int32",m)]}},aj={kernelName:ts,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:i}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(1!==a.shape.length)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(0!==i.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const o=n.readSync(a.dataId),u=n.readSync(i.dataId)[0],[l,c,h]=XL(o,u,s),p=c.length;return[n.makeTensorInfo([p,2],"int32",l),n.makeTensorInfo([p],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(h))]}},ij={kernelName:ns,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{numBuckets:s}=r,{input:a}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");const i=n.readSync(a.dataId),o=YL(i,s);return n.makeTensorInfo(a.shape,"int32",o)}},oj=Yz({opSnippet:"return tan(x);"}),uj={kernelName:ss,backendName:"webgl",kernelFunc:oj},lj=Yz({opSnippet:"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n"}),cj={kernelName:as,backendName:"webgl",kernelFunc:lj},hj={kernelName:Ar,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{tensor:s,indices:a,updates:i}=t,{}=r,{sliceRank:o,numUpdates:u,sliceSize:l,strides:c,outputSize:h}=pl(0,a,s.shape),p=[h/l,l];if(0===h)return n.makeTensorInfo(s.shape,a.dtype);const d=aP({inputs:{x:a},backend:n,attrs:{shape:[u,o]}}),f=aP({inputs:{x:i},backend:n,attrs:{shape:[u,l]}}),m=aP({inputs:{x:s},backend:n,attrs:{shape:p}}),g=new wG(u,o,d.shape.length,f.shape.length,c,p,!1,!0),y=n.runWebGLProgram(g,[f,d,m],m.dtype),b=aP({inputs:{x:y},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),b}};class pj{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[r]*t[r];this.outputShape=n,this.rank=n.length;const r=IM(this.rank),s=function(e){const t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(1===t)return`imod(resRC, ${e[0]})`;const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[];for(let t=0;t<e.length;t++)r.push(`imod(${n[t]}, ${e[t]})`);return r.join()}(e);this.userCode=`\n void main() {\n ${r} resRC = getOutputCoords();\n setOutput(getA(${s}));\n }\n `}}function dj(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;if("string"===s.dtype||s.shape.length>5){const e=n.readSync(s.dataId),t="string"===s.dtype?e.map((e=>ta(e))):e,r=Mo(s.shape,s.dtype,t),i=ZL(r,a);return n.makeTensorInfo(i.shape,i.dtype,i.values)}const i=new pj(s.shape,a);return n.runWebGLProgram(i,[s],s.dtype)}const fj={kernelName:is,backendName:"webgl",kernelFunc:dj};class mj{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int elemIdx = coords[1];\n\n // We compare elements pair-wise within a group of size 2 * inc.\n // The comparing rule for each group alternates between ascending\n // and descending. Within each group, we compare each pair at\n // positions i and i+inc. To decide whether an element at position i\n // is x0 or x1, we mod it by 2 * inc, if the result is smaller than\n // inc, it is in the first half of the group, we denote it as x0,\n // otherwise we denote it as x1.\n // For example, as shown in the Bitonic top K paper referenced above,\n // Figure5(a) shows that element[1] is in the\n // second half of the group when group size is 2, but it is in the\n // first half of the group when group size is 4.\n\n bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;\n int i = isFirstInPair ? elemIdx : elemIdx - inc;\n\n int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\n int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));\n float x0 = i0 < n ? getX(batch, i0) : negativeInf;\n float x1 = i1 < n ? getX(batch, i1) : negativeInf;\n\n // Denotes which direction indices are in (ascending or descending).\n bool reverse = imod(elemIdx, 2 * dir) >= dir;\n bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);\n if (reverse == isGreater) { // Elements in opposite order of direction\n int iTemp = i0;\n i0 = i1;\n i1 = iTemp;\n }\n if (isFirstInPair) {\n setOutput(float(i0));\n } else {\n setOutput(float(i1));\n }\n }\n "}}class gj{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode="\n void main() {\n // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int elemIdx = coords[1];\n\n // The output size is half of the previous size.\n // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),\n // we only need to output the indices at positions |, the indices at\n // positions _ can be thrown away, see Figure5(b) After Phase 2\n // (Merge phase) in the Bitonic Top K paper referenced above.\n // For example, the paper shows we only need to output the orange bars.\n // The output sequence should look like this | | | | | | | |.\n // Because the sequence is halved, to map the output index back\n // to the previous sequence to find the corresponding value,\n // we need to double the index. When we double the index,\n // we basically interpolate a position, so 2i looks like\n // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position\n // of each 2k positions by - elemIdx % k. E.g. for output at\n // index 4,5,6,7, we want to get the corresponding element at\n // original index 8,9,10,11, for output at index 8,9,10,11,\n // we want to get the corresponding element at original index\n // 16,17,18,19, so on and so forth.\n\n int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));\n int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\n int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));\n\n float x0 = getX(batch, i0);\n float x1 = i1 < n ? getX(batch, i1) : x0;\n\n setOutput(x0 >= x1 ? float(i0) : float(i1));\n }\n "}}function yj(e,t){null!==t&&e.disposeIntermediateTensorInfo(t)}function bj(e){let t=1;for(;t<e;)t*=2;return t}const xj={kernelName:os,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:i}=r,o=Ye().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),u=Ye().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),l=s.shape,c=l[l.length-1];if(n.shouldExecuteOnCPU([s])||c<o||a>u){const e=n.readSync(s.dataId),[t,r]=QL(e,l,s.dtype,a,i);return[n.makeTensorInfo(t.shape,t.dtype,t.values),n.makeTensorInfo(r.shape,r.dtype,r.values)]}if(0===a)return l[l.length-1]=0,[n.makeTensorInfo(l,s.dtype,[]),n.makeTensorInfo(l,"int32",[])];if(1===c)return[s,YW({attrs:{shape:l,dtype:"int32",value:0},backend:n})];const h=n.texData.get(s.dataId),p=null!==h&&h.isPacked,d=p?n.unpackTensor(s):s,f=le(l)/c,m=aP({inputs:{x:d},attrs:{shape:[f,c]},backend:n});p&&yj(n,d);const g=bj(a),y=bj(c);let b=null;const x=()=>null===b?[m,m]:[m,b],w=(e,t,r)=>{const s=x(),a=new mj(r),i=[[c],[null===b?1:0],[Number.NEGATIVE_INFINITY],[e],[t]],o=b;b=n.runWebGLProgram(a,s,"int32",i),yj(n,o)};for(let e=1;e<g;e*=2){const t=2*e;for(let n=e;n>=1;n/=2)w(t,n,[f,y])}for(let e=y;e>g;e/=2){const t=x(),r=new gj([f,e/2]),s=[[c],[null===b?1:0],[g]],a=b;b=n.runWebGLProgram(r,t,"int32",s),yj(n,a);const i=g/2,o=2*i;for(let e=i;e>=1;e/=2)w(o,e,b.shape)}let v=b;b=pB({inputs:{x:b},backend:n,attrs:{begin:0,size:[f,a]}}),yj(n,v);let k=mU({inputs:{x:m,indices:b},backend:n,attrs:{axis:1,batchDims:1}});yj(n,m);const I=l.slice(0,-1);I.push(a),v=b,b=aP({inputs:{x:b},attrs:{shape:I},backend:n}),yj(n,v);const N=k;return k=aP({inputs:{x:k},attrs:{shape:I},backend:n}),yj(n,N),[k,b]}};class wj{constructor(e,t,n,r,s,a){this.variableNames=["Image","Transforms"],this.outputShape=a;const i="nearest"===n?1:2;let o;switch(r){case"constant":default:o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4}this.userCode=`\n float mapCoord(float outCoord, float len) {\n float inCoord = outCoord;\n if(${o} == 2) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n if (inCoord < sz2) {\n inCoord = sz2 * float(int(float(-inCoord / sz2))) +\n inCoord;\n }\n inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n inCoord -= sz2 * float(int(float(inCoord / sz2)));\n if (inCoord >= len) {\n inCoord = sz2 - inCoord - 1.0;\n }\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${o} == 3) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord -= len * float(int(float(inCoord / sz)));\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${o} == 4) {\n return clamp(outCoord, 0.0, len - 1.0);\n } else {\n return outCoord;\n }\n }\n\n float readWithFillValue(int batch, int coordY, int coordX,\n int channel) {\n float outputValue;\n if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {\n outputValue = getImage(batch, coordY, coordX, channel);\n } else {\n outputValue = float(${s});\n }\n return outputValue;\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n float outputValue;\n int batch = coords[0];\n int x = coords[2];\n int y = coords[1];\n int channel = coords[3];\n float xf = float(x);\n float yf = float(y);\n float a1 = getTransforms(batch, 0);\n float a2 = getTransforms(batch, 1);\n float a3 = getTransforms(batch, 2);\n float b1 = getTransforms(batch, 3);\n float b2 = getTransforms(batch, 4);\n float b3 = getTransforms(batch, 5);\n float c1 = getTransforms(batch, 6);\n float c2 = getTransforms(batch, 7);\n float projection = c1 * xf + c2 * yf + 1.0;\n if (projection == 0.0) {\n outputValue = float(${s});\n } else {\n float inX = (a1 * xf + a2 * yf + a3) / projection;\n float inY = (b1 * xf + b2 * yf + b3) / projection;\n float mapX = mapCoord(inX, float(${t}));\n float mapY = mapCoord(inY, float(${e}));\n\n if (${i} == 1) {\n int coordY = int(round(mapY));\n int coordX = int(round(mapX));\n outputValue = readWithFillValue(batch, coordY, coordX,\n channel);\n } else {\n float yFloor = floor(mapY);\n float xFloor = floor(mapX);\n float yCeil = yFloor + 1.0;\n float xCeil = xFloor + 1.0;\n float valueYFloor = (xCeil - mapX) *\n readWithFillValue(batch, int(yFloor), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yFloor), int(xCeil), channel);\n float valueYCeil = (xCeil - mapX) *\n readWithFillValue(batch, int(yCeil), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yCeil), int(xCeil), channel);\n outputValue = (yCeil - mapY) * valueYFloor +\n (mapY - yFloor) * valueYCeil;\n }\n }\n setOutput(outputValue);\n }\n `}}const vj={kernelName:us,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:s,transforms:a}=t,{interpolation:i,fillMode:o,fillValue:u,outputShape:l}=r,[c,h,p,d]=s.shape,[f,m]=null!=l?l:[h,p],g=new wj(h,p,i,o,u,[c,f,m,d]);return n.runWebGLProgram(g,[s,a],"float32")}};var kj=n(96763);const Ij={kernelName:cs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;iM(a,"unique"),kj.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const i=r.readSync(a.dataId),{outputValues:o,outputShape:u,indices:l}=tz(i,s,a.shape,a.dtype);return[r.makeTensorInfo(u,a.dtype,o),r.makeTensorInfo([l.length],"int32",l)]}},Nj={kernelName:hs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:s}=t;let{axis:a}=r;a<0&&(a+=s.shape.length);const i=s,o=i.shape.length,u=s.shape[a],l=new Array(o-1);let c=0;for(let e=0;e<o;e++)e!==a&&(l[c++]=i.shape[e]);const h=[],p=new Array(o).fill(0),d=i.shape.slice();d[a]=1;const f=new Array(u);for(let e=0;e<f.length;e++){p[a]=e;const t=pB({inputs:{x:i},backend:n,attrs:{begin:p,size:d}}),r=aP({inputs:{x:t},backend:n,attrs:{shape:l}});f[e]=r,h.push(t)}return h.forEach((e=>n.disposeIntermediateTensorInfo(e))),f}};class Sj{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,r=e.batchSize,s=e.inSize,a=e.numSegments,i=a*Math.ceil(s/n);this.outputShape=[r,i];const o=4*Math.floor(n/4),u=n%4,l="\n sumValue += dot(values, segFilter);\n ";let c="";s%n>0&&(c=`\n if (inIdx < 0 || inIdx >= ${s}) {\n return initializationValue;\n }\n `);let h="";s%n>0&&(h=`\n if (inIdx < 0 || inIdx >= ${s}) {\n return -1.0;\n }\n `),this.userCode=`\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n ${c}\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n ${h}\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n ${a})) * float(${n}));\n int currentSeg = int(mod(float(outIdx), float(${a})));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${o}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n ${l}\n }\n\n int inIdx = inOffset + ${o};\n if (${1===u}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n ${l}\n } else if (${2===u}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n ${l}\n } else if (${3===u}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n ${l}\n }\n setOutput(sumValue);\n }\n `}}const Tj={kernelName:ps,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:i}=r,o=s.shape.length,u=[];let l=0;const c=xh([l],o);let h=s;null!=c&&(h=mP({inputs:{x:s},backend:n,attrs:{perm:c}}),u.push(h),l=vh(1,o)[0]);const p=og(h.shape,l,i),d=le([h.shape[l]]),f=aP({inputs:{x:h},backend:n,attrs:{shape:[-1,d]}});u.push(f);const m=Aa(s.dtype),g=(e,t,r,s,a)=>{const i=e.shape[0],o=e.shape[1],l=ig(o,a),c=new Sj({windowSize:l,inSize:o,batchSize:i,numSegments:a},t),h=n.compileAndRun(c,[e,r],s);if(u.push(h),h.shape[1]===a)return h;const p=qV({backend:n,attrs:{start:0,stop:a,step:1,dtype:"float32"}}),d=dj({inputs:{x:p},backend:n,attrs:{reps:[o/l]}});return u.push(p),u.push(d),g(h,t,d,s,a)},y=aP({inputs:{x:g(f,"unsortedSegmentSum",a,m,i)},backend:n,attrs:{shape:p}});let b=y;if(null!=c){u.push(y);const e=wh(c);b=mP({inputs:{x:b},backend:n,attrs:{perm:e}})}return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),b}},Cj=[xP,vP,IP,SP,$P,RP,OP,FP,PP,BP,UP,GP,HP,KP,YP,QP,eB,rB,sB,aB,uB,fB,mB,gB,yB,kB,SB,$B,Uz,RB,PB,qB,ZB,eW,tW,nW,rW,aW,oW,lW,mW,gW,yW,xW,kW,SW,TW,$W,AW,RW,FW,_W,MW,zW,BW,UW,jW,KW,JW,QW,nU,sU,oU,cU,hU,dU,gU,bU,wU,Bz,vU,MB,IU,SU,CU,jz,EU,RU,OU,_U,MU,zU,BU,UU,jU,qU,XU,JU,ZU,QU,nV,rV,sV,aV,iV,uV,hV,dV,kV,sP,NV,TV,$V,AV,xB,OV,DV,MV,BV,UV,Kz,VV,GV,jV,HV,KV,vB,gV,YV,ZV,eG,iP,rG,aG,uG,cG,dG,mG,yG,xG,kG,NG,TG,$G,AG,OG,_G,MG,dB,vV,zG,PG,BG,WG,UG,VG,GG,jG,KG,YG,QG,ej,tj,rj,sj,aj,ij,xV,fP,uj,cj,hj,fj,xj,vj,gP,Ij,Nj,Tj,_V];for(const e of Cj)Es(e);const $j={"tfjs-core":Hl,"tfjs-backend-cpu":GA,"tfjs-backend-webgl":Oz,"tfjs-data":g$,"tfjs-layers":Jw,"tfjs-converter":oC,tfjs:"4.20.0"}},34529:(e,t,n)=>{"use strict";var r=n(11514)();function s(e,t){if(e===t)return 0;for(var n=e.length,r=t.length,s=0,a=Math.min(n,r);s<a;++s)if(e[s]!==t[s]){n=e[s],r=t[s];break}return n<r?-1:r<n?1:0}function a(e){return n.g.Buffer&&"function"==typeof n.g.Buffer.isBuffer?n.g.Buffer.isBuffer(e):!(null==e||!e._isBuffer)}var i=n(94591),o=Object.prototype.hasOwnProperty,u=Array.prototype.slice,l="foo"===function(){}.name;function c(e){return Object.prototype.toString.call(e)}function h(e){return!a(e)&&"function"==typeof n.g.ArrayBuffer&&("function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):!!e&&(e instanceof DataView||!!(e.buffer&&e.buffer instanceof ArrayBuffer)))}var p=e.exports=b,d=/\s*function\s+([^\(\s]*)\s*/;function f(e){if(i.isFunction(e)){if(l)return e.name;var t=e.toString().match(d);return t&&t[1]}}function m(e,t){return"string"==typeof e?e.length<t?e:e.slice(0,t):e}function g(e){if(l||!i.isFunction(e))return i.inspect(e);var t=f(e);return"[Function"+(t?": "+t:"")+"]"}function y(e,t,n,r,s){throw new p.AssertionError({message:n,actual:e,expected:t,operator:r,stackStartFunction:s})}function b(e,t){e||y(e,!0,t,"==",p.ok)}function x(e,t,n,r){if(e===t)return!0;if(a(e)&&a(t))return 0===s(e,t);if(i.isDate(e)&&i.isDate(t))return e.getTime()===t.getTime();if(i.isRegExp(e)&&i.isRegExp(t))return e.source===t.source&&e.global===t.global&&e.multiline===t.multiline&&e.lastIndex===t.lastIndex&&e.ignoreCase===t.ignoreCase;if(null!==e&&"object"==typeof e||null!==t&&"object"==typeof t){if(h(e)&&h(t)&&c(e)===c(t)&&!(e instanceof Float32Array||e instanceof Float64Array))return 0===s(new Uint8Array(e.buffer),new Uint8Array(t.buffer));if(a(e)!==a(t))return!1;var o=(r=r||{actual:[],expected:[]}).actual.indexOf(e);return-1!==o&&o===r.expected.indexOf(t)||(r.actual.push(e),r.expected.push(t),function(e,t,n,r){if(null==e||null==t)return!1;if(i.isPrimitive(e)||i.isPrimitive(t))return e===t;if(n&&Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1;var s=w(e),a=w(t);if(s&&!a||!s&&a)return!1;if(s)return x(e=u.call(e),t=u.call(t),n);var o,l,c=I(e),h=I(t);if(c.length!==h.length)return!1;for(c.sort(),h.sort(),l=c.length-1;l>=0;l--)if(c[l]!==h[l])return!1;for(l=c.length-1;l>=0;l--)if(!x(e[o=c[l]],t[o],n,r))return!1;return!0}(e,t,n,r))}return n?e===t:e==t}function w(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function v(e,t){if(!e||!t)return!1;if("[object RegExp]"==Object.prototype.toString.call(t))return t.test(e);try{if(e instanceof t)return!0}catch(e){}return!Error.isPrototypeOf(t)&&!0===t.call({},e)}function k(e,t,n,r){var s;if("function"!=typeof t)throw new TypeError('"block" argument must be a function');"string"==typeof n&&(r=n,n=null),s=function(e){var t;try{e()}catch(e){t=e}return t}(t),r=(n&&n.name?" ("+n.name+").":".")+(r?" "+r:"."),e&&!s&&y(s,n,"Missing expected exception"+r);var a="string"==typeof r,o=!e&&s&&!n;if((!e&&i.isError(s)&&a&&v(s,n)||o)&&y(s,n,"Got unwanted exception"+r),e&&s&&n&&!v(s,n)||!e&&s)throw s}p.AssertionError=function(e){this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=function(e){return m(g(e.actual),128)+" "+e.operator+" "+m(g(e.expected),128)}(this),this.generatedMessage=!0);var t=e.stackStartFunction||y;if(Error.captureStackTrace)Error.captureStackTrace(this,t);else{var n=new Error;if(n.stack){var r=n.stack,s=f(t),a=r.indexOf("\n"+s);if(a>=0){var i=r.indexOf("\n",a+1);r=r.substring(i+1)}this.stack=r}}},i.inherits(p.AssertionError,Error),p.fail=y,p.ok=b,p.equal=function(e,t,n){e!=t&&y(e,t,n,"==",p.equal)},p.notEqual=function(e,t,n){e==t&&y(e,t,n,"!=",p.notEqual)},p.deepEqual=function(e,t,n){x(e,t,!1)||y(e,t,n,"deepEqual",p.deepEqual)},p.deepStrictEqual=function(e,t,n){x(e,t,!0)||y(e,t,n,"deepStrictEqual",p.deepStrictEqual)},p.notDeepEqual=function(e,t,n){x(e,t,!1)&&y(e,t,n,"notDeepEqual",p.notDeepEqual)},p.notDeepStrictEqual=function e(t,n,r){x(t,n,!0)&&y(t,n,r,"notDeepStrictEqual",e)},p.strictEqual=function(e,t,n){e!==t&&y(e,t,n,"===",p.strictEqual)},p.notStrictEqual=function(e,t,n){e===t&&y(e,t,n,"!==",p.notStrictEqual)},p.throws=function(e,t,n){k(!0,e,t,n)},p.doesNotThrow=function(e,t,n){k(!1,e,t,n)},p.ifError=function(e){if(e)throw e},p.strict=r((function e(t,n){t||y(t,!0,n,"==",e)}),p,{equal:p.strictEqual,deepEqual:p.deepStrictEqual,notEqual:p.notStrictEqual,notDeepEqual:p.notDeepStrictEqual}),p.strict.strict=p.strict;var I=Object.keys||function(e){var t=[];for(var n in e)o.call(e,n)&&t.push(n);return t}},26100:e=>{"function"==typeof Object.create?e.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},33845:e=>{e.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},94591:(e,t,n)=>{var r=n(65606),s=n(96763),a=/%[sdj%]/g;t.format=function(e){if(!b(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(u(arguments[n]));return t.join(" ")}n=1;for(var r=arguments,s=r.length,i=String(e).replace(a,(function(e){if("%%"===e)return"%";if(n>=s)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(e){return"[Circular]"}default:return e}})),o=r[n];n<s;o=r[++n])g(o)||!v(o)?i+=" "+o:i+=" "+u(o);return i},t.deprecate=function(e,a){if(x(n.g.process))return function(){return t.deprecate(e,a).apply(this,arguments)};if(!0===r.noDeprecation)return e;var i=!1;return function(){if(!i){if(r.throwDeprecation)throw new Error(a);r.traceDeprecation?s.trace(a):s.error(a),i=!0}return e.apply(this,arguments)}};var i,o={};function u(e,n){var r={seen:[],stylize:c};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),m(n)?r.showHidden=n:n&&t._extend(r,n),x(r.showHidden)&&(r.showHidden=!1),x(r.depth)&&(r.depth=2),x(r.colors)&&(r.colors=!1),x(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=l),h(r,e,r.depth)}function l(e,t){var n=u.styles[t];return n?"["+u.colors[n][0]+"m"+e+"["+u.colors[n][1]+"m":e}function c(e,t){return e}function h(e,n,r){if(e.customInspect&&n&&N(n.inspect)&&n.inspect!==t.inspect&&(!n.constructor||n.constructor.prototype!==n)){var s=n.inspect(r,e);return b(s)||(s=h(e,s,r)),s}var a=function(e,t){if(x(t))return e.stylize("undefined","undefined");if(b(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return y(t)?e.stylize(""+t,"number"):m(t)?e.stylize(""+t,"boolean"):g(t)?e.stylize("null","null"):void 0}(e,n);if(a)return a;var i=Object.keys(n),o=function(e){var t={};return e.forEach((function(e,n){t[e]=!0})),t}(i);if(e.showHidden&&(i=Object.getOwnPropertyNames(n)),I(n)&&(i.indexOf("message")>=0||i.indexOf("description")>=0))return p(n);if(0===i.length){if(N(n)){var u=n.name?": "+n.name:"";return e.stylize("[Function"+u+"]","special")}if(w(n))return e.stylize(RegExp.prototype.toString.call(n),"regexp");if(k(n))return e.stylize(Date.prototype.toString.call(n),"date");if(I(n))return p(n)}var l,c="",v=!1,S=["{","}"];return f(n)&&(v=!0,S=["[","]"]),N(n)&&(c=" [Function"+(n.name?": "+n.name:"")+"]"),w(n)&&(c=" "+RegExp.prototype.toString.call(n)),k(n)&&(c=" "+Date.prototype.toUTCString.call(n)),I(n)&&(c=" "+p(n)),0!==i.length||v&&0!=n.length?r<0?w(n)?e.stylize(RegExp.prototype.toString.call(n),"regexp"):e.stylize("[Object]","special"):(e.seen.push(n),l=v?function(e,t,n,r,s){for(var a=[],i=0,o=t.length;i<o;++i)$(t,String(i))?a.push(d(e,t,n,r,String(i),!0)):a.push("");return s.forEach((function(s){s.match(/^\d+$/)||a.push(d(e,t,n,r,s,!0))})),a}(e,n,r,o,i):i.map((function(t){return d(e,n,r,o,t,v)})),e.seen.pop(),function(e,t,n){return e.reduce((function(e,t){return t.indexOf("\n"),e+t.replace(/\u001b\[\d\d?m/g,"").length+1}),0)>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}(l,c,S)):S[0]+c+S[1]}function p(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,n,r,s,a){var i,o,u;if((u=Object.getOwnPropertyDescriptor(t,s)||{value:t[s]}).get?o=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(o=e.stylize("[Setter]","special")),$(r,s)||(i="["+s+"]"),o||(e.seen.indexOf(u.value)<0?(o=g(n)?h(e,u.value,null):h(e,u.value,n-1)).indexOf("\n")>-1&&(o=a?o.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+o.split("\n").map((function(e){return" "+e})).join("\n")):o=e.stylize("[Circular]","special")),x(i)){if(a&&s.match(/^\d+$/))return o;(i=JSON.stringify(""+s)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(i=i.substr(1,i.length-2),i=e.stylize(i,"name")):(i=i.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),i=e.stylize(i,"string"))}return i+": "+o}function f(e){return Array.isArray(e)}function m(e){return"boolean"==typeof e}function g(e){return null===e}function y(e){return"number"==typeof e}function b(e){return"string"==typeof e}function x(e){return void 0===e}function w(e){return v(e)&&"[object RegExp]"===S(e)}function v(e){return"object"==typeof e&&null!==e}function k(e){return v(e)&&"[object Date]"===S(e)}function I(e){return v(e)&&("[object Error]"===S(e)||e instanceof Error)}function N(e){return"function"==typeof e}function S(e){return Object.prototype.toString.call(e)}function T(e){return e<10?"0"+e.toString(10):e.toString(10)}t.debuglog=function(e){if(x(i)&&(i=r.env.NODE_DEBUG||""),e=e.toUpperCase(),!o[e])if(new RegExp("\\b"+e+"\\b","i").test(i)){var n=r.pid;o[e]=function(){var r=t.format.apply(t,arguments);s.error("%s %d: %s",e,n,r)}}else o[e]=function(){};return o[e]},t.inspect=u,u.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},u.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},t.isArray=f,t.isBoolean=m,t.isNull=g,t.isNullOrUndefined=function(e){return null==e},t.isNumber=y,t.isString=b,t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=x,t.isRegExp=w,t.isObject=v,t.isDate=k,t.isError=I,t.isFunction=N,t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=n(33845);var C=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function $(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.log=function(){var e,n;s.log("%s - %s",(n=[T((e=new Date).getHours()),T(e.getMinutes()),T(e.getSeconds())].join(":"),[e.getDate(),C[e.getMonth()],n].join(" ")),t.format.apply(t,arguments))},t.inherits=n(26100),t._extend=function(e,t){if(!t||!v(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}},61813:(e,t,n)=>{"use strict";n.r(t),n.d(t,{NSFW_CLASSES:()=>r});const r={0:"Drawing",1:"Hentai",2:"Neutral",3:"Porn",4:"Sexy"}},89793:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return s(t,e),t},i=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,a){function i(e){try{u(r.next(e))}catch(e){a(e)}}function o(e){try{u(r.throw(e))}catch(e){a(e)}}function u(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,o)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,s,a,i={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(u){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,o[0]&&(i=0)),i;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,r=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!((s=(s=i.trys).length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){i=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){i.label=o[1];break}if(6===o[0]&&i.label<s[1]){i.label=s[1],s=o;break}if(s&&i.label<s[2]){i.label=s[2],i.ops.push(o);break}s[2]&&i.ops.pop(),i.trys.pop();continue}o=t.call(e,i)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,u])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.NSFWJS=t.load=void 0;var u=a(n(99951)),l=n(61813);t.load=function(e,t){return void 0===e&&(e="https://d1zv2aa70wpiur.cloudfront.net/tfjs_quant_nsfw_mobilenet/"),void 0===t&&(t={size:224}),i(this,void 0,void 0,(function(){var n;return o(this,(function(r){switch(r.label){case 0:if(null==u)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this model.");return t.size=t.size||224,[4,(n=new c(e,t)).load()];case 1:return r.sent(),[2,n]}}))}))};var c=function(){function e(e,t){this.intermediateModels={},this.options=t,this.normalizationOffset=u.scalar(255),"string"!=typeof e||e.startsWith("indexeddb://")||e.startsWith("localstorage://")||e.endsWith("model.json")?this.pathOrIOHandler=e:this.pathOrIOHandler="".concat(e,"model.json")}return e.prototype.load=function(){return i(this,void 0,void 0,(function(){var e,t,n,r,s,a=this;return o(this,(function(i){switch(i.label){case 0:return e=this.options,t=e.size,"graph"!==e.type?[3,2]:(n=this,[4,u.loadGraphModel(this.pathOrIOHandler)]);case 1:return n.model=i.sent(),[3,4];case 2:return r=this,[4,u.loadLayersModel(this.pathOrIOHandler)];case 3:r.model=i.sent(),this.endpoints=this.model.layers.map((function(e){return e.name})),i.label=4;case 4:return[4,(s=u.tidy((function(){return a.model.predict(u.zeros([1,t,t,3]))}))).data()];case 5:return i.sent(),s.dispose(),[2]}}))}))},e.prototype.infer=function(e,t){var n=this;if(null!=t&&-1===this.endpoints.indexOf(t))throw new Error("Unknown endpoint ".concat(t,". Available endpoints: ")+"".concat(this.endpoints,"."));return u.tidy((function(){e instanceof u.Tensor||(e=u.browser.fromPixels(e));var r=e.toFloat().div(n.normalizationOffset),s=r,a=n.options.size;e.shape[0]===a&&e.shape[1]===a||(s=u.image.resizeBilinear(r,[a,a],!0));var i,o=s.reshape([1,a,a,3]);if(null==t)i=n.model;else{if(n.model.hasOwnProperty("layers")&&null==n.intermediateModels[t]){var l=n.model.layers.find((function(e){return e.name===t}));n.intermediateModels[t]=u.model({inputs:n.model.inputs,outputs:l.output})}i=n.intermediateModels[t]}return i.predict(o)}))},e.prototype.classify=function(e,t){return void 0===t&&(t=5),i(this,void 0,void 0,(function(){var n,r;return o(this,(function(s){switch(s.label){case 0:return[4,h(n=this.infer(e),t)];case 1:return r=s.sent(),n.dispose(),[2,r]}}))}))},e}();function h(e,t){return i(this,void 0,void 0,(function(){var n,r,s,a,i,u;return o(this,(function(o){switch(o.label){case 0:return[4,e.data()];case 1:for(n=o.sent(),r=[],u=0;u<n.length;u++)r.push({value:n[u],index:u});for(r.sort((function(e,t){return t.value-e.value})),s=new Float32Array(t),a=new Int32Array(t),u=0;u<t;u++)s[u]=r[u].value,a[u]=r[u].index;for(i=[],u=0;u<a.length;u++)i.push({className:l.NSFW_CLASSES[a[u]],probability:s[u]});return[2,i]}}))}))}t.NSFWJS=c},67526:(e,t)=>{"use strict";t.byteLength=function(e){var t=o(e),n=t[0],r=t[1];return 3*(n+r)/4-r},t.toByteArray=function(e){var t,n,a=o(e),i=a[0],u=a[1],l=new s(function(e,t,n){return 3*(t+n)/4-n}(0,i,u)),c=0,h=u>0?i-4:i;for(n=0;n<h;n+=4)t=r[e.charCodeAt(n)]<<18|r[e.charCodeAt(n+1)]<<12|r[e.charCodeAt(n+2)]<<6|r[e.charCodeAt(n+3)],l[c++]=t>>16&255,l[c++]=t>>8&255,l[c++]=255&t;return 2===u&&(t=r[e.charCodeAt(n)]<<2|r[e.charCodeAt(n+1)]>>4,l[c++]=255&t),1===u&&(t=r[e.charCodeAt(n)]<<10|r[e.charCodeAt(n+1)]<<4|r[e.charCodeAt(n+2)]>>2,l[c++]=t>>8&255,l[c++]=255&t),l},t.fromByteArray=function(e){for(var t,r=e.length,s=r%3,a=[],i=16383,o=0,l=r-s;o<l;o+=i)a.push(u(e,o,o+i>l?l:o+i));return 1===s?(t=e[r-1],a.push(n[t>>2]+n[t<<4&63]+"==")):2===s&&(t=(e[r-2]<<8)+e[r-1],a.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),a.join("")};for(var n=[],r=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)n[i]=a[i],r[a.charCodeAt(i)]=i;function o(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function u(e,t,r){for(var s,a,i=[],o=t;o<r;o+=3)s=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),i.push(n[(a=s)>>18&63]+n[a>>12&63]+n[a>>6&63]+n[63&a]);return i.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},38075:(e,t,n)=>{"use strict";var r=n(70453),s=n(10487),a=s(r("String.prototype.indexOf"));e.exports=function(e,t){var n=r(e,!!t);return"function"==typeof n&&a(e,".prototype.")>-1?s(n):n}},10487:(e,t,n)=>{"use strict";var r=n(66743),s=n(70453),a=n(96897),i=n(69675),o=s("%Function.prototype.apply%"),u=s("%Function.prototype.call%"),l=s("%Reflect.apply%",!0)||r.call(u,o),c=n(30655),h=s("%Math.max%");e.exports=function(e){if("function"!=typeof e)throw new i("a function is required");var t=l(r,u,arguments);return a(t,1+h(0,e.length-(arguments.length-1)),!0)};var p=function(){return l(r,o,arguments)};c?c(e.exports,"apply",{value:p}):e.exports.apply=p},96763:(e,t,n)=>{var r=n(40537),s=n(34529);function a(){return(new Date).getTime()}var i,o=Array.prototype.slice,u={};i=void 0!==n.g&&n.g.console?n.g.console:"undefined"!=typeof window&&window.console?window.console:{};for(var l=[[function(){},"log"],[function(){i.log.apply(i,arguments)},"info"],[function(){i.log.apply(i,arguments)},"warn"],[function(){i.warn.apply(i,arguments)},"error"],[function(e){u[e]=a()},"time"],[function(e){var t=u[e];if(!t)throw new Error("No such label: "+e);delete u[e];var n=a()-t;i.log(e+": "+n+"ms")},"timeEnd"],[function(){var e=new Error;e.name="Trace",e.message=r.format.apply(null,arguments),i.error(e.stack)},"trace"],[function(e){i.log(r.inspect(e)+"\n")},"dir"],[function(e){if(!e){var t=o.call(arguments,1);s.ok(!1,r.format.apply(null,t))}},"assert"]],c=0;c<l.length;c++){var h=l[c],p=h[0],d=h[1];i[d]||(i[d]=p)}e.exports=i},30041:(e,t,n)=>{"use strict";var r=n(30655),s=n(58068),a=n(69675),i=n(75795);e.exports=function(e,t,n){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new a("`obj` must be an object or a function`");if("string"!=typeof t&&"symbol"!=typeof t)throw new a("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new a("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new a("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new a("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new a("`loose`, if provided, must be a boolean");var o=arguments.length>3?arguments[3]:null,u=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,c=arguments.length>6&&arguments[6],h=!!i&&i(e,t);if(r)r(e,t,{configurable:null===l&&h?h.configurable:!l,enumerable:null===o&&h?h.enumerable:!o,value:n,writable:null===u&&h?h.writable:!u});else{if(!c&&(o||u||l))throw new s("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");e[t]=n}}},30655:(e,t,n)=>{"use strict";var r=n(70453)("%Object.defineProperty%",!0)||!1;if(r)try{r({},"a",{value:1})}catch(e){r=!1}e.exports=r},41237:e=>{"use strict";e.exports=EvalError},69383:e=>{"use strict";e.exports=Error},79290:e=>{"use strict";e.exports=RangeError},79538:e=>{"use strict";e.exports=ReferenceError},58068:e=>{"use strict";e.exports=SyntaxError},69675:e=>{"use strict";e.exports=TypeError},35345:e=>{"use strict";e.exports=URIError},89353:e=>{"use strict";var t=Object.prototype.toString,n=Math.max,r=function(e,t){for(var n=[],r=0;r<e.length;r+=1)n[r]=e[r];for(var s=0;s<t.length;s+=1)n[s+e.length]=t[s];return n};e.exports=function(e){var s=this;if("function"!=typeof s||"[object Function]"!==t.apply(s))throw new TypeError("Function.prototype.bind called on incompatible "+s);for(var a,i=function(e,t){for(var n=[],r=1,s=0;r<e.length;r+=1,s+=1)n[s]=e[r];return n}(arguments),o=n(0,s.length-i.length),u=[],l=0;l<o;l++)u[l]="$"+l;if(a=Function("binder","return function ("+function(e,t){for(var n="",r=0;r<e.length;r+=1)n+=e[r],r+1<e.length&&(n+=",");return n}(u)+"){ return binder.apply(this,arguments); }")((function(){if(this instanceof a){var t=s.apply(this,r(i,arguments));return Object(t)===t?t:this}return s.apply(e,r(i,arguments))})),s.prototype){var c=function(){};c.prototype=s.prototype,a.prototype=new c,c.prototype=null}return a}},66743:(e,t,n)=>{"use strict";var r=n(89353);e.exports=Function.prototype.bind||r},70453:(e,t,n)=>{"use strict";var r,s=n(69383),a=n(41237),i=n(79290),o=n(79538),u=n(58068),l=n(69675),c=n(35345),h=Function,p=function(e){try{return h('"use strict"; return ('+e+").constructor;")()}catch(e){}},d=Object.getOwnPropertyDescriptor;if(d)try{d({},"")}catch(e){d=null}var f=function(){throw new l},m=d?function(){try{return f}catch(e){try{return d(arguments,"callee").get}catch(e){return f}}}():f,g=n(64039)(),y=n(80024)(),b=Object.getPrototypeOf||(y?function(e){return e.__proto__}:null),x={},w="undefined"!=typeof Uint8Array&&b?b(Uint8Array):r,v={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?r:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?r:ArrayBuffer,"%ArrayIteratorPrototype%":g&&b?b([][Symbol.iterator]()):r,"%AsyncFromSyncIteratorPrototype%":r,"%AsyncFunction%":x,"%AsyncGenerator%":x,"%AsyncGeneratorFunction%":x,"%AsyncIteratorPrototype%":x,"%Atomics%":"undefined"==typeof Atomics?r:Atomics,"%BigInt%":"undefined"==typeof BigInt?r:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?r:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?r:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?r:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":s,"%eval%":eval,"%EvalError%":a,"%Float32Array%":"undefined"==typeof Float32Array?r:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?r:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?r:FinalizationRegistry,"%Function%":h,"%GeneratorFunction%":x,"%Int8Array%":"undefined"==typeof Int8Array?r:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?r:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?r:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":g&&b?b(b([][Symbol.iterator]())):r,"%JSON%":"object"==typeof JSON?JSON:r,"%Map%":"undefined"==typeof Map?r:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&g&&b?b((new Map)[Symbol.iterator]()):r,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?r:Promise,"%Proxy%":"undefined"==typeof Proxy?r:Proxy,"%RangeError%":i,"%ReferenceError%":o,"%Reflect%":"undefined"==typeof Reflect?r:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?r:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&g&&b?b((new Set)[Symbol.iterator]()):r,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?r:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":g&&b?b(""[Symbol.iterator]()):r,"%Symbol%":g?Symbol:r,"%SyntaxError%":u,"%ThrowTypeError%":m,"%TypedArray%":w,"%TypeError%":l,"%Uint8Array%":"undefined"==typeof Uint8Array?r:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?r:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?r:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?r:Uint32Array,"%URIError%":c,"%WeakMap%":"undefined"==typeof WeakMap?r:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?r:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?r:WeakSet};if(b)try{null.error}catch(e){var k=b(b(e));v["%Error.prototype%"]=k}var I=function e(t){var n;if("%AsyncFunction%"===t)n=p("async function () {}");else if("%GeneratorFunction%"===t)n=p("function* () {}");else if("%AsyncGeneratorFunction%"===t)n=p("async function* () {}");else if("%AsyncGenerator%"===t){var r=e("%AsyncGeneratorFunction%");r&&(n=r.prototype)}else if("%AsyncIteratorPrototype%"===t){var s=e("%AsyncGenerator%");s&&b&&(n=b(s.prototype))}return v[t]=n,n},N={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},S=n(66743),T=n(9957),C=S.call(Function.call,Array.prototype.concat),$=S.call(Function.apply,Array.prototype.splice),E=S.call(Function.call,String.prototype.replace),A=S.call(Function.call,String.prototype.slice),R=S.call(Function.call,RegExp.prototype.exec),O=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,F=/\\(\\)?/g,_=function(e,t){var n,r=e;if(T(N,r)&&(r="%"+(n=N[r])[0]+"%"),T(v,r)){var s=v[r];if(s===x&&(s=I(r)),void 0===s&&!t)throw new l("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:n,name:r,value:s}}throw new u("intrinsic "+e+" does not exist!")};e.exports=function(e,t){if("string"!=typeof e||0===e.length)throw new l("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new l('"allowMissing" argument must be a boolean');if(null===R(/^%?[^%]*%?$/,e))throw new u("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=function(e){var t=A(e,0,1),n=A(e,-1);if("%"===t&&"%"!==n)throw new u("invalid intrinsic syntax, expected closing `%`");if("%"===n&&"%"!==t)throw new u("invalid intrinsic syntax, expected opening `%`");var r=[];return E(e,O,(function(e,t,n,s){r[r.length]=n?E(s,F,"$1"):t||e})),r}(e),r=n.length>0?n[0]:"",s=_("%"+r+"%",t),a=s.name,i=s.value,o=!1,c=s.alias;c&&(r=c[0],$(n,C([0,1],c)));for(var h=1,p=!0;h<n.length;h+=1){var f=n[h],m=A(f,0,1),g=A(f,-1);if(('"'===m||"'"===m||"`"===m||'"'===g||"'"===g||"`"===g)&&m!==g)throw new u("property names with quotes must have matching quotes");if("constructor"!==f&&p||(o=!0),T(v,a="%"+(r+="."+f)+"%"))i=v[a];else if(null!=i){if(!(f in i)){if(!t)throw new l("base intrinsic for "+e+" exists, but the property is not available.");return}if(d&&h+1>=n.length){var y=d(i,f);i=(p=!!y)&&"get"in y&&!("originalValue"in y.get)?y.get:i[f]}else p=T(i,f),i=i[f];p&&!o&&(v[a]=i)}}return i}},75795:(e,t,n)=>{"use strict";var r=n(70453)("%Object.getOwnPropertyDescriptor%",!0);if(r)try{r([],"length")}catch(e){r=null}e.exports=r},30592:(e,t,n)=>{"use strict";var r=n(30655),s=function(){return!!r};s.hasArrayLengthDefineBug=function(){if(!r)return null;try{return 1!==r([],"length",{value:1}).length}catch(e){return!0}},e.exports=s},80024:e=>{"use strict";var t={__proto__:null,foo:{}},n=Object;e.exports=function(){return{__proto__:t}.foo===t.foo&&!(t instanceof n)}},64039:(e,t,n)=>{"use strict";var r="undefined"!=typeof Symbol&&Symbol,s=n(41333);e.exports=function(){return"function"==typeof r&&"function"==typeof Symbol&&"symbol"==typeof r("foo")&&"symbol"==typeof Symbol("bar")&&s()}},41333:e=>{"use strict";e.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),n=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(n))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var r=Object.getOwnPropertySymbols(e);if(1!==r.length||r[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var s=Object.getOwnPropertyDescriptor(e,t);if(42!==s.value||!0!==s.enumerable)return!1}return!0}},9957:(e,t,n)=>{"use strict";var r=Function.prototype.call,s=Object.prototype.hasOwnProperty,a=n(66743);e.exports=a.call(r,s)},251:(e,t)=>{t.read=function(e,t,n,r,s){var a,i,o=8*s-r-1,u=(1<<o)-1,l=u>>1,c=-7,h=n?s-1:0,p=n?-1:1,d=e[t+h];for(h+=p,a=d&(1<<-c)-1,d>>=-c,c+=o;c>0;a=256*a+e[t+h],h+=p,c-=8);for(i=a&(1<<-c)-1,a>>=-c,c+=r;c>0;i=256*i+e[t+h],h+=p,c-=8);if(0===a)a=1-l;else{if(a===u)return i?NaN:1/0*(d?-1:1);i+=Math.pow(2,r),a-=l}return(d?-1:1)*i*Math.pow(2,a-r)},t.write=function(e,t,n,r,s,a){var i,o,u,l=8*a-s-1,c=(1<<l)-1,h=c>>1,p=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:a-1,f=r?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,i=c):(i=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-i))<1&&(i--,u*=2),(t+=i+h>=1?p/u:p*Math.pow(2,1-h))*u>=2&&(i++,u/=2),i+h>=c?(o=0,i=c):i+h>=1?(o=(t*u-1)*Math.pow(2,s),i+=h):(o=t*Math.pow(2,h-1)*Math.pow(2,s),i=0));s>=8;e[n+d]=255&o,d+=f,o/=256,s-=8);for(i=i<<s|o,l+=s;l>0;e[n+d]=255&i,d+=f,i/=256,l-=8);e[n+d-f]|=128*m}},28570:e=>{e.exports=n;var t=null;try{t=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(e){}function n(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function r(e){return!0===(e&&e.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=r;var s={},a={};function i(e,t){var n,r,i;return t?(i=0<=(e>>>=0)&&e<256)&&(r=a[e])?r:(n=u(e,(0|e)<0?-1:0,!0),i&&(a[e]=n),n):(i=-128<=(e|=0)&&e<128)&&(r=s[e])?r:(n=u(e,e<0?-1:0,!1),i&&(s[e]=n),n)}function o(e,t){if(isNaN(e))return t?y:g;if(t){if(e<0)return y;if(e>=d)return k}else{if(e<=-f)return I;if(e+1>=f)return v}return e<0?o(-e,t).neg():u(e%p|0,e/p|0,t)}function u(e,t,r){return new n(e,t,r)}n.fromInt=i,n.fromNumber=o,n.fromBits=u;var l=Math.pow;function c(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return g;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||36<n)throw RangeError("radix");var r;if((r=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===r)return c(e.substring(1),t,n).neg();for(var s=o(l(n,8)),a=g,i=0;i<e.length;i+=8){var u=Math.min(8,e.length-i),h=parseInt(e.substring(i,i+u),n);if(u<8){var p=o(l(n,u));a=a.mul(p).add(o(h))}else a=(a=a.mul(s)).add(o(h))}return a.unsigned=t,a}function h(e,t){return"number"==typeof e?o(e,t):"string"==typeof e?c(e,t):u(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}n.fromString=c,n.fromValue=h;var p=4294967296,d=p*p,f=d/2,m=i(1<<24),g=i(0);n.ZERO=g;var y=i(0,!0);n.UZERO=y;var b=i(1);n.ONE=b;var x=i(1,!0);n.UONE=x;var w=i(-1);n.NEG_ONE=w;var v=u(-1,2147483647,!1);n.MAX_VALUE=v;var k=u(-1,-1,!0);n.MAX_UNSIGNED_VALUE=k;var I=u(0,-2147483648,!1);n.MIN_VALUE=I;var N=n.prototype;N.toInt=function(){return this.unsigned?this.low>>>0:this.low},N.toNumber=function(){return this.unsigned?(this.high>>>0)*p+(this.low>>>0):this.high*p+(this.low>>>0)},N.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(I)){var t=o(e),n=this.div(t),r=n.mul(t).sub(this);return n.toString(e)+r.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var s=o(l(e,6),this.unsigned),a=this,i="";;){var u=a.div(s),c=(a.sub(u.mul(s)).toInt()>>>0).toString(e);if((a=u).isZero())return c+i;for(;c.length<6;)c="0"+c;i=""+c+i}},N.getHighBits=function(){return this.high},N.getHighBitsUnsigned=function(){return this.high>>>0},N.getLowBits=function(){return this.low},N.getLowBitsUnsigned=function(){return this.low>>>0},N.getNumBitsAbs=function(){if(this.isNegative())return this.eq(I)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},N.isZero=function(){return 0===this.high&&0===this.low},N.eqz=N.isZero,N.isNegative=function(){return!this.unsigned&&this.high<0},N.isPositive=function(){return this.unsigned||this.high>=0},N.isOdd=function(){return!(1&~this.low)},N.isEven=function(){return!(1&this.low)},N.equals=function(e){return r(e)||(e=h(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},N.eq=N.equals,N.notEquals=function(e){return!this.eq(e)},N.neq=N.notEquals,N.ne=N.notEquals,N.lessThan=function(e){return this.comp(e)<0},N.lt=N.lessThan,N.lessThanOrEqual=function(e){return this.comp(e)<=0},N.lte=N.lessThanOrEqual,N.le=N.lessThanOrEqual,N.greaterThan=function(e){return this.comp(e)>0},N.gt=N.greaterThan,N.greaterThanOrEqual=function(e){return this.comp(e)>=0},N.gte=N.greaterThanOrEqual,N.ge=N.greaterThanOrEqual,N.compare=function(e){if(r(e)||(e=h(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},N.comp=N.compare,N.negate=function(){return!this.unsigned&&this.eq(I)?I:this.not().add(b)},N.neg=N.negate,N.add=function(e){r(e)||(e=h(e));var t=this.high>>>16,n=65535&this.high,s=this.low>>>16,a=65535&this.low,i=e.high>>>16,o=65535&e.high,l=e.low>>>16,c=0,p=0,d=0,f=0;return d+=(f+=a+(65535&e.low))>>>16,p+=(d+=s+l)>>>16,c+=(p+=n+o)>>>16,c+=t+i,u((d&=65535)<<16|(f&=65535),(c&=65535)<<16|(p&=65535),this.unsigned)},N.subtract=function(e){return r(e)||(e=h(e)),this.add(e.neg())},N.sub=N.subtract,N.multiply=function(e){if(this.isZero())return g;if(r(e)||(e=h(e)),t)return u(t.mul(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned);if(e.isZero())return g;if(this.eq(I))return e.isOdd()?I:g;if(e.eq(I))return this.isOdd()?I:g;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(m)&&e.lt(m))return o(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,s=65535&this.high,a=this.low>>>16,i=65535&this.low,l=e.high>>>16,c=65535&e.high,p=e.low>>>16,d=65535&e.low,f=0,y=0,b=0,x=0;return b+=(x+=i*d)>>>16,y+=(b+=a*d)>>>16,b&=65535,y+=(b+=i*p)>>>16,f+=(y+=s*d)>>>16,y&=65535,f+=(y+=a*p)>>>16,y&=65535,f+=(y+=i*c)>>>16,f+=n*d+s*p+a*c+i*l,u((b&=65535)<<16|(x&=65535),(f&=65535)<<16|(y&=65535),this.unsigned)},N.mul=N.multiply,N.divide=function(e){if(r(e)||(e=h(e)),e.isZero())throw Error("division by zero");var n,s,a;if(t)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?u((this.unsigned?t.div_u:t.div_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?y:g;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return y;if(e.gt(this.shru(1)))return x;a=y}else{if(this.eq(I))return e.eq(b)||e.eq(w)?I:e.eq(I)?b:(n=this.shr(1).div(e).shl(1)).eq(g)?e.isNegative()?b:w:(s=this.sub(e.mul(n)),a=n.add(s.div(e)));if(e.eq(I))return this.unsigned?y:g;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();a=g}for(s=this;s.gte(e);){n=Math.max(1,Math.floor(s.toNumber()/e.toNumber()));for(var i=Math.ceil(Math.log(n)/Math.LN2),c=i<=48?1:l(2,i-48),p=o(n),d=p.mul(e);d.isNegative()||d.gt(s);)d=(p=o(n-=c,this.unsigned)).mul(e);p.isZero()&&(p=b),a=a.add(p),s=s.sub(d)}return a},N.div=N.divide,N.modulo=function(e){return r(e)||(e=h(e)),t?u((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},N.mod=N.modulo,N.rem=N.modulo,N.not=function(){return u(~this.low,~this.high,this.unsigned)},N.and=function(e){return r(e)||(e=h(e)),u(this.low&e.low,this.high&e.high,this.unsigned)},N.or=function(e){return r(e)||(e=h(e)),u(this.low|e.low,this.high|e.high,this.unsigned)},N.xor=function(e){return r(e)||(e=h(e)),u(this.low^e.low,this.high^e.high,this.unsigned)},N.shiftLeft=function(e){return r(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?u(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):u(0,this.low<<e-32,this.unsigned)},N.shl=N.shiftLeft,N.shiftRight=function(e){return r(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?u(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):u(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},N.shr=N.shiftRight,N.shiftRightUnsigned=function(e){if(r(e)&&(e=e.toInt()),0==(e&=63))return this;var t=this.high;return e<32?u(this.low>>>e|t<<32-e,t>>>e,this.unsigned):u(32===e?t:t>>>e-32,0,this.unsigned)},N.shru=N.shiftRightUnsigned,N.shr_u=N.shiftRightUnsigned,N.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},N.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},N.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},N.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},N.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},n.fromBytes=function(e,t,r){return r?n.fromBytesLE(e,t):n.fromBytesBE(e,t)},n.fromBytesLE=function(e,t){return new n(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},n.fromBytesBE=function(e,t){return new n(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}},62045:(e,t,n)=>{"use strict";var r=n(96763);const s=n(67526),a=n(251),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=l,t.IS=50;const o=2147483647;function u(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,l.prototype),t}function l(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return p(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!l.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|g(e,t);let r=u(n);const s=r.write(e,t);return s!==n&&(r=r.slice(0,s)),r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(Y(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return d(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Y(e,ArrayBuffer)||e&&Y(e.buffer,ArrayBuffer))return f(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(Y(e,SharedArrayBuffer)||e&&Y(e.buffer,SharedArrayBuffer)))return f(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return l.from(r,t,n);const s=function(e){if(l.isBuffer(e)){const t=0|m(e.length),n=u(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||J(e.length)?u(0):d(e):"Buffer"===e.type&&Array.isArray(e.data)?d(e.data):void 0}(e);if(s)return s;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return l.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function h(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function p(e){return h(e),u(e<0?0:0|m(e))}function d(e){const t=e.length<0?0:0|m(e.length),n=u(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function f(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,l.prototype),r}function m(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function g(e,t){if(l.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Y(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let s=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return q(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return K(e).length;default:if(s)return r?-1:q(e).length;t=(""+t).toLowerCase(),s=!0}}function y(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return R(this,t,n);case"utf8":case"utf-8":return C(this,t,n);case"ascii":return E(this,t,n);case"latin1":case"binary":return A(this,t,n);case"base64":return T(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function b(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function x(e,t,n,r,s){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),J(n=+n)&&(n=s?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(s)return-1;n=e.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof t&&(t=l.from(t,r)),l.isBuffer(t))return 0===t.length?-1:w(e,t,n,r,s);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):w(e,[t],n,r,s);throw new TypeError("val must be string, number or Buffer")}function w(e,t,n,r,s){let a,i=1,o=e.length,u=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;i=2,o/=2,u/=2,n/=2}function l(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(s){let r=-1;for(a=n;a<o;a++)if(l(e,a)===l(t,-1===r?0:a-r)){if(-1===r&&(r=a),a-r+1===u)return r*i}else-1!==r&&(a-=a-r),r=-1}else for(n+u>o&&(n=o-u),a=n;a>=0;a--){let n=!0;for(let r=0;r<u;r++)if(l(e,a+r)!==l(t,r)){n=!1;break}if(n)return a}return-1}function v(e,t,n,r){n=Number(n)||0;const s=e.length-n;r?(r=Number(r))>s&&(r=s):r=s;const a=t.length;let i;for(r>a/2&&(r=a/2),i=0;i<r;++i){const r=parseInt(t.substr(2*i,2),16);if(J(r))return i;e[n+i]=r}return i}function k(e,t,n,r){return X(q(t,e.length-n),e,n,r)}function I(e,t,n,r){return X(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function N(e,t,n,r){return X(K(t),e,n,r)}function S(e,t,n,r){return X(function(e,t){let n,r,s;const a=[];for(let i=0;i<e.length&&!((t-=2)<0);++i)n=e.charCodeAt(i),r=n>>8,s=n%256,a.push(s),a.push(r);return a}(t,e.length-n),e,n,r)}function T(e,t,n){return 0===t&&n===e.length?s.fromByteArray(e):s.fromByteArray(e.slice(t,n))}function C(e,t,n){n=Math.min(e.length,n);const r=[];let s=t;for(;s<n;){const t=e[s];let a=null,i=t>239?4:t>223?3:t>191?2:1;if(s+i<=n){let n,r,o,u;switch(i){case 1:t<128&&(a=t);break;case 2:n=e[s+1],128==(192&n)&&(u=(31&t)<<6|63&n,u>127&&(a=u));break;case 3:n=e[s+1],r=e[s+2],128==(192&n)&&128==(192&r)&&(u=(15&t)<<12|(63&n)<<6|63&r,u>2047&&(u<55296||u>57343)&&(a=u));break;case 4:n=e[s+1],r=e[s+2],o=e[s+3],128==(192&n)&&128==(192&r)&&128==(192&o)&&(u=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&o,u>65535&&u<1114112&&(a=u))}}null===a?(a=65533,i=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|1023&a),r.push(a),s+=i}return function(e){const t=e.length;if(t<=$)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=$));return n}(r)}l.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),l.TYPED_ARRAY_SUPPORT||void 0===r||"function"!=typeof r.error||r.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}}),l.poolSize=8192,l.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array),l.alloc=function(e,t,n){return function(e,t,n){return h(e),e<=0?u(e):void 0!==t?"string"==typeof n?u(e).fill(t,n):u(e).fill(t):u(e)}(e,t,n)},l.allocUnsafe=function(e){return p(e)},l.allocUnsafeSlow=function(e){return p(e)},l.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==l.prototype},l.compare=function(e,t){if(Y(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),Y(t,Uint8Array)&&(t=l.from(t,t.offset,t.byteLength)),!l.isBuffer(e)||!l.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let s=0,a=Math.min(n,r);s<a;++s)if(e[s]!==t[s]){n=e[s],r=t[s];break}return n<r?-1:r<n?1:0},l.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return l.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=l.allocUnsafe(t);let s=0;for(n=0;n<e.length;++n){let t=e[n];if(Y(t,Uint8Array))s+t.length>r.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(r,s)):Uint8Array.prototype.set.call(r,t,s);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,s)}s+=t.length}return r},l.byteLength=g,l.prototype._isBuffer=!0,l.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)b(this,t,t+1);return this},l.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)b(this,t,t+3),b(this,t+1,t+2);return this},l.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)b(this,t,t+7),b(this,t+1,t+6),b(this,t+2,t+5),b(this,t+3,t+4);return this},l.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?C(this,0,e):y.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.prototype.inspect=function(){let e="";const n=t.IS;return e=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(e+=" ... "),"<Buffer "+e+">"},i&&(l.prototype[i]=l.prototype.inspect),l.prototype.compare=function(e,t,n,r,s){if(Y(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),!l.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),t<0||n>e.length||r<0||s>this.length)throw new RangeError("out of range index");if(r>=s&&t>=n)return 0;if(r>=s)return-1;if(t>=n)return 1;if(this===e)return 0;let a=(s>>>=0)-(r>>>=0),i=(n>>>=0)-(t>>>=0);const o=Math.min(a,i),u=this.slice(r,s),c=e.slice(t,n);for(let e=0;e<o;++e)if(u[e]!==c[e]){a=u[e],i=c[e];break}return a<i?-1:i<a?1:0},l.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},l.prototype.indexOf=function(e,t,n){return x(this,e,t,n,!0)},l.prototype.lastIndexOf=function(e,t,n){return x(this,e,t,n,!1)},l.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const s=this.length-t;if((void 0===n||n>s)&&(n=s),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let a=!1;for(;;)switch(r){case"hex":return v(this,e,t,n);case"utf8":case"utf-8":return k(this,e,t,n);case"ascii":case"latin1":case"binary":return I(this,e,t,n);case"base64":return N(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(a)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),a=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const $=4096;function E(e,t,n){let r="";n=Math.min(e.length,n);for(let s=t;s<n;++s)r+=String.fromCharCode(127&e[s]);return r}function A(e,t,n){let r="";n=Math.min(e.length,n);for(let s=t;s<n;++s)r+=String.fromCharCode(e[s]);return r}function R(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let s="";for(let r=t;r<n;++r)s+=Z[e[r]];return s}function O(e,t,n){const r=e.slice(t,n);let s="";for(let e=0;e<r.length-1;e+=2)s+=String.fromCharCode(r[e]+256*r[e+1]);return s}function F(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function _(e,t,n,r,s,a){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||t<a)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function D(e,t,n,r,s){V(t,r,s,e,n,7);let a=Number(t&BigInt(4294967295));e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a;let i=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,i>>=8,e[n++]=i,n}function M(e,t,n,r,s){V(t,r,s,e,n,7);let a=Number(t&BigInt(4294967295));e[n+7]=a,a>>=8,e[n+6]=a,a>>=8,e[n+5]=a,a>>=8,e[n+4]=a;let i=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=i,i>>=8,e[n+2]=i,i>>=8,e[n+1]=i,i>>=8,e[n]=i,n+8}function L(e,t,n,r,s,a){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function z(e,t,n,r,s){return t=+t,n>>>=0,s||L(e,0,n,4),a.write(e,t,n,r,23,4),n+4}function P(e,t,n,r,s){return t=+t,n>>>=0,s||L(e,0,n,8),a.write(e,t,n,r,52,8),n+8}l.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,l.prototype),r},l.prototype.readUintLE=l.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||F(e,t,this.length);let r=this[e],s=1,a=0;for(;++a<t&&(s*=256);)r+=this[e+a]*s;return r},l.prototype.readUintBE=l.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||F(e,t,this.length);let r=this[e+--t],s=1;for(;t>0&&(s*=256);)r+=this[e+--t]*s;return r},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||F(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||F(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||F(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||F(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(e,t){return e>>>=0,t||F(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=Q((function(e){G(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||j(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,s=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(s)<<BigInt(32))})),l.prototype.readBigUInt64BE=Q((function(e){G(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||j(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],s=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(s)})),l.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||F(e,t,this.length);let r=this[e],s=1,a=0;for(;++a<t&&(s*=256);)r+=this[e+a]*s;return s*=128,r>=s&&(r-=Math.pow(2,8*t)),r},l.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||F(e,t,this.length);let r=t,s=1,a=this[e+--r];for(;r>0&&(s*=256);)a+=this[e+--r]*s;return s*=128,a>=s&&(a-=Math.pow(2,8*t)),a},l.prototype.readInt8=function(e,t){return e>>>=0,t||F(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||F(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt16BE=function(e,t){e>>>=0,t||F(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt32LE=function(e,t){return e>>>=0,t||F(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return e>>>=0,t||F(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=Q((function(e){G(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||j(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)})),l.prototype.readBigInt64BE=Q((function(e){G(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||j(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)})),l.prototype.readFloatLE=function(e,t){return e>>>=0,t||F(e,4,this.length),a.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||F(e,4,this.length),a.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||F(e,8,this.length),a.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||F(e,8,this.length),a.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||_(this,e,t,n,Math.pow(2,8*n)-1,0);let s=1,a=0;for(this[t]=255&e;++a<n&&(s*=256);)this[t+a]=e/s&255;return t+n},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||_(this,e,t,n,Math.pow(2,8*n)-1,0);let s=n-1,a=1;for(this[t+s]=255&e;--s>=0&&(a*=256);)this[t+s]=e/a&255;return t+n},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,255,0),this[t]=255&e,t+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigUInt64LE=Q((function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeBigUInt64BE=Q((function(e,t=0){return M(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);_(this,e,t,n,r-1,-r)}let s=0,a=1,i=0;for(this[t]=255&e;++s<n&&(a*=256);)e<0&&0===i&&0!==this[t+s-1]&&(i=1),this[t+s]=(e/a|0)-i&255;return t+n},l.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);_(this,e,t,n,r-1,-r)}let s=n-1,a=1,i=0;for(this[t+s]=255&e;--s>=0&&(a*=256);)e<0&&0===i&&0!==this[t+s+1]&&(i=1),this[t+s]=(e/a|0)-i&255;return t+n},l.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},l.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigInt64LE=Q((function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),l.prototype.writeBigInt64BE=Q((function(e,t=0){return M(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),l.prototype.writeFloatLE=function(e,t,n){return z(this,e,t,!0,n)},l.prototype.writeFloatBE=function(e,t,n){return z(this,e,t,!1,n)},l.prototype.writeDoubleLE=function(e,t,n){return P(this,e,t,!0,n)},l.prototype.writeDoubleBE=function(e,t,n){return P(this,e,t,!1,n)},l.prototype.copy=function(e,t,n,r){if(!l.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const s=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),s},l.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!l.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{const a=l.isBuffer(e)?e:l.from(e,r),i=a.length;if(0===i)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=a[s%i]}return this};const B={};function W(e,t,n){B[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function U(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function V(e,t,n,r,s,a){if(e>n||e<t){const r="bigint"==typeof t?"n":"";let s;throw s=a>3?0===t||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(a+1)}${r}`:`>= -(2${r} ** ${8*(a+1)-1}${r}) and < 2 ** ${8*(a+1)-1}${r}`:`>= ${t}${r} and <= ${n}${r}`,new B.ERR_OUT_OF_RANGE("value",s,e)}!function(e,t,n){G(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||j(t,e.length-(n+1))}(r,s,a)}function G(e,t){if("number"!=typeof e)throw new B.ERR_INVALID_ARG_TYPE(t,"number",e)}function j(e,t,n){if(Math.floor(e)!==e)throw G(e,n),new B.ERR_OUT_OF_RANGE(n||"offset","an integer",e);if(t<0)throw new B.ERR_BUFFER_OUT_OF_BOUNDS;throw new B.ERR_OUT_OF_RANGE(n||"offset",`>= ${n?1:0} and <= ${t}`,e)}W("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),W("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),W("ERR_OUT_OF_RANGE",(function(e,t,n){let r=`The value of "${e}" is out of range.`,s=n;return Number.isInteger(n)&&Math.abs(n)>2**32?s=U(String(n)):"bigint"==typeof n&&(s=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(s=U(s)),s+="n"),r+=` It must be ${t}. Received ${s}`,r}),RangeError);const H=/[^+/0-9A-Za-z-_]/g;function q(e,t){let n;t=t||1/0;const r=e.length;let s=null;const a=[];for(let i=0;i<r;++i){if(n=e.charCodeAt(i),n>55295&&n<57344){if(!s){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(i+1===r){(t-=3)>-1&&a.push(239,191,189);continue}s=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),s=n;continue}n=65536+(s-55296<<10|n-56320)}else s&&(t-=3)>-1&&a.push(239,191,189);if(s=null,n<128){if((t-=1)<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return a}function K(e){return s.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(H,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function X(e,t,n,r){let s;for(s=0;s<r&&!(s+n>=t.length||s>=e.length);++s)t[s+n]=e[s];return s}function Y(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function J(e){return e!=e}const Z=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let s=0;s<16;++s)t[r+s]=e[n]+e[s]}return t}();function Q(e){return"undefined"==typeof BigInt?ee:e}function ee(){throw new Error("BigInt not supported")}},28875:(e,t,n)=>{"use strict";var r;if(!Object.keys){var s=Object.prototype.hasOwnProperty,a=Object.prototype.toString,i=n(1093),o=Object.prototype.propertyIsEnumerable,u=!o.call({toString:null},"toString"),l=o.call((function(){}),"prototype"),c=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],h=function(e){var t=e.constructor;return t&&t.prototype===e},p={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},d=function(){if("undefined"==typeof window)return!1;for(var e in window)try{if(!p["$"+e]&&s.call(window,e)&&null!==window[e]&&"object"==typeof window[e])try{h(window[e])}catch(e){return!0}}catch(e){return!0}return!1}();r=function(e){var t=null!==e&&"object"==typeof e,n="[object Function]"===a.call(e),r=i(e),o=t&&"[object String]"===a.call(e),p=[];if(!t&&!n&&!r)throw new TypeError("Object.keys called on a non-object");var f=l&&n;if(o&&e.length>0&&!s.call(e,0))for(var m=0;m<e.length;++m)p.push(String(m));if(r&&e.length>0)for(var g=0;g<e.length;++g)p.push(String(g));else for(var y in e)f&&"prototype"===y||!s.call(e,y)||p.push(String(y));if(u)for(var b=function(e){if("undefined"==typeof window||!d)return h(e);try{return h(e)}catch(e){return!1}}(e),x=0;x<c.length;++x)b&&"constructor"===c[x]||!s.call(e,c[x])||p.push(c[x]);return p}}e.exports=r},1189:(e,t,n)=>{"use strict";var r=Array.prototype.slice,s=n(1093),a=Object.keys,i=a?function(e){return a(e)}:n(28875),o=Object.keys;i.shim=function(){if(Object.keys){var e=function(){var e=Object.keys(arguments);return e&&e.length===arguments.length}(1,2);e||(Object.keys=function(e){return s(e)?o(r.call(e)):o(e)})}else Object.keys=i;return Object.keys||i},e.exports=i},1093:e=>{"use strict";var t=Object.prototype.toString;e.exports=function(e){var n=t.call(e),r="[object Arguments]"===n;return r||(r="[object Array]"!==n&&null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Function]"===t.call(e.callee)),r}},38403:(e,t,n)=>{"use strict";var r=n(1189),s=n(41333)(),a=n(38075),i=Object,o=a("Array.prototype.push"),u=a("Object.prototype.propertyIsEnumerable"),l=s?Object.getOwnPropertySymbols:null;e.exports=function(e,t){if(null==e)throw new TypeError("target must be an object");var n=i(e);if(1===arguments.length)return n;for(var a=1;a<arguments.length;++a){var c=i(arguments[a]),h=r(c),p=s&&(Object.getOwnPropertySymbols||l);if(p)for(var d=p(c),f=0;f<d.length;++f){var m=d[f];u(c,m)&&o(h,m)}for(var g=0;g<h.length;++g){var y=h[g];if(u(c,y)){var b=c[y];n[y]=b}}}return n}},11514:(e,t,n)=>{"use strict";var r=n(38403);e.exports=function(){return Object.assign?function(){if(!Object.assign)return!1;for(var e="abcdefghijklmnopqrst",t=e.split(""),n={},r=0;r<t.length;++r)n[t[r]]=t[r];var s=Object.assign({},n),a="";for(var i in s)a+=i;return e!==a}()||function(){if(!Object.assign||!Object.preventExtensions)return!1;var e=Object.preventExtensions({1:2});try{Object.assign(e,"xy")}catch(t){return"y"===e[1]}return!1}()?r:Object.assign:r}},65606:e=>{var t,n,r=e.exports={};function s(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function i(e){if(t===setTimeout)return setTimeout(e,0);if((t===s||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(n){try{return t.call(null,e,0)}catch(n){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:s}catch(e){t=s}try{n="function"==typeof clearTimeout?clearTimeout:a}catch(e){n=a}}();var o,u=[],l=!1,c=-1;function h(){l&&o&&(l=!1,o.length?u=o.concat(u):c=-1,u.length&&p())}function p(){if(!l){var e=i(h);l=!0;for(var t=u.length;t;){for(o=u,u=[];++c<t;)o&&o[c].run();c=-1,t=u.length}o=null,l=!1,function(e){if(n===clearTimeout)return clearTimeout(e);if((n===a||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(e);try{return n(e)}catch(t){try{return n.call(null,e)}catch(t){return n.call(this,e)}}}(e)}}function d(e,t){this.fun=e,this.array=t}function f(){}r.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];u.push(new d(e,t)),1!==u.length||l||i(p)},d.prototype.run=function(){this.fun.apply(null,this.array)},r.title="browser",r.browser=!0,r.env={},r.argv=[],r.version="",r.versions={},r.on=f,r.addListener=f,r.once=f,r.off=f,r.removeListener=f,r.removeAllListeners=f,r.emit=f,r.prependListener=f,r.prependOnceListener=f,r.listeners=function(e){return[]},r.binding=function(e){throw new Error("process.binding is not supported")},r.cwd=function(){return"/"},r.chdir=function(e){throw new Error("process.chdir is not supported")},r.umask=function(){return 0}},7391:(e,t,n)=>{var r=n(7180),s=n(43181),a=n(43031),i=n(9067),o=n(96833),u=n(43717),l=n(74801);l.alea=r,l.xor128=s,l.xorwow=a,l.xorshift7=i,l.xor4096=o,l.tychei=u,e.exports=l},7180:function(e,t,n){var r;!function(e,s,a){function i(e){var t,n=this,r=(t=4022871197,function(e){e=String(e);for(var n=0;n<e.length;n++){var r=.02519603282416938*(t+=e.charCodeAt(n));r-=t=r>>>0,t=(r*=t)>>>0,t+=4294967296*(r-=t)}return 2.3283064365386963e-10*(t>>>0)});n.next=function(){var e=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=e-(n.c=0|e)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(e),n.s0<0&&(n.s0+=1),n.s1-=r(e),n.s1<0&&(n.s1+=1),n.s2-=r(e),n.s2<0&&(n.s2+=1),r=null}function o(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function u(e,t){var n=new i(e),r=t&&t.state,s=n.next;return s.int32=function(){return 4294967296*n.next()|0},s.double=function(){return s()+11102230246251565e-32*(2097152*s()|0)},s.quick=s,r&&("object"==typeof r&&o(r,n),s.state=function(){return o(n,{})}),s}s&&s.exports?s.exports=u:n.amdD&&n.amdO?void 0===(r=function(){return u}.call(t,n,t,s))||(s.exports=r):this.alea=u}(0,e=n.nmd(e),n.amdD)},43717:function(e,t,n){var r;!function(e,s,a){function i(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,s=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^s,s=s-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^s,t.a=s-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r<n.length+20;r++)t.b^=0|n.charCodeAt(r),t.next()}function o(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function u(e,t){var n=new i(e),r=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,r&&("object"==typeof r&&o(r,n),s.state=function(){return o(n,{})}),s}s&&s.exports?s.exports=u:n.amdD&&n.amdO?void 0===(r=function(){return u}.call(t,n,t,s))||(s.exports=r):this.tychei=u}(0,e=n.nmd(e),n.amdD)},43181:function(e,t,n){var r;!function(e,s,a){function i(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),t.next()}function o(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function u(e,t){var n=new i(e),r=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,r&&("object"==typeof r&&o(r,n),s.state=function(){return o(n,{})}),s}s&&s.exports?s.exports=u:n.amdD&&n.amdO?void 0===(r=function(){return u}.call(t,n,t,s))||(s.exports=r):this.xor128=u}(0,e=n.nmd(e),n.amdD)},96833:function(e,t,n){var r;!function(e,s,a){function i(e){var t=this;t.next=function(){var e,n,r=t.w,s=t.X,a=t.i;return t.w=r=r+1640531527|0,n=s[a+34&127],e=s[a=a+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=s[a]=n^e,t.i=a,n+(r^r>>>16)|0},function(e,t){var n,r,s,a,i,o=[],u=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,u=Math.max(u,t.length)),s=0,a=-32;a<u;++a)t&&(r^=t.charCodeAt((a+32)%t.length)),0===a&&(i=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(i=i+1640531527|0,s=0==(n=o[127&a]^=r+i)?s+1:0);for(s>=128&&(o[127&(t&&t.length||0)]=-1),s=127,a=512;a>0;--a)r=o[s+34&127],n=o[s=s+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,o[s]=r^n;e.w=i,e.X=o,e.i=s}(t,e)}function o(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function u(e,t){null==e&&(e=+new Date);var n=new i(e),r=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,r&&(r.X&&o(r,n),s.state=function(){return o(n,{})}),s}s&&s.exports?s.exports=u:n.amdD&&n.amdO?void 0===(r=function(){return u}.call(t,n,t,s))||(s.exports=r):this.xor4096=u}(0,e=n.nmd(e),n.amdD)},9067:function(e,t,n){var r;!function(e,s,a){function i(e){var t=this;t.next=function(){var e,n,r=t.x,s=t.i;return e=r[s],n=(e^=e>>>7)^e<<24,n^=(e=r[s+1&7])^e>>>10,n^=(e=r[s+3&7])^e>>>3,n^=(e=r[s+4&7])^e<<7,e=r[s+7&7],n^=(e^=e<<13)^e<<9,r[s]=n,t.i=s+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n<t.length;++n)r[7&n]=r[7&n]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}(t,e)}function o(e,t){return t.x=e.x.slice(),t.i=e.i,t}function u(e,t){null==e&&(e=+new Date);var n=new i(e),r=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,r&&(r.x&&o(r,n),s.state=function(){return o(n,{})}),s}s&&s.exports?s.exports=u:n.amdD&&n.amdO?void 0===(r=function(){return u}.call(t,n,t,s))||(s.exports=r):this.xorshift7=u}(0,e=n.nmd(e),n.amdD)},43031:function(e,t,n){var r;!function(e,s,a){function i(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function o(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function u(e,t){var n=new i(e),r=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,r&&("object"==typeof r&&o(r,n),s.state=function(){return o(n,{})}),s}s&&s.exports?s.exports=u:n.amdD&&n.amdO?void 0===(r=function(){return u}.call(t,n,t,s))||(s.exports=r):this.xorwow=u}(0,e=n.nmd(e),n.amdD)},74801:function(e,t,n){var r;!function(s,a,i){var o,u=256,l=i.pow(u,6),c=i.pow(2,52),h=2*c,p=u-1;function d(e,t,n){var r=[],p=y(g((t=1==t?{entropy:!0}:t||{}).entropy?[e,b(a)]:null==e?function(){try{var e;return o&&(e=o.randomBytes)?e=e(u):(e=new Uint8Array(u),(s.crypto||s.msCrypto).getRandomValues(e)),b(e)}catch(e){var t=s.navigator,n=t&&t.plugins;return[+new Date,s,n,s.screen,b(a)]}}():e,3),r),d=new f(r),x=function(){for(var e=d.g(6),t=l,n=0;e<c;)e=(e+n)*u,t*=u,n=d.g(1);for(;e>=h;)e/=2,t/=2,n>>>=1;return(e+n)/t};return x.int32=function(){return 0|d.g(4)},x.quick=function(){return d.g(4)/4294967296},x.double=x,y(b(d.S),a),(t.pass||n||function(e,t,n,r){return r&&(r.S&&m(r,d),e.state=function(){return m(d,{})}),n?(i.random=e,t):e})(x,p,"global"in t?t.global:this==i,t.state)}function f(e){var t,n=e.length,r=this,s=0,a=r.i=r.j=0,i=r.S=[];for(n||(e=[n++]);s<u;)i[s]=s++;for(s=0;s<u;s++)i[s]=i[a=p&a+e[s%n]+(t=i[s])],i[a]=t;(r.g=function(e){for(var t,n=0,s=r.i,a=r.j,i=r.S;e--;)t=i[s=p&s+1],n=n*u+i[p&(i[s]=i[a=p&a+t])+(i[a]=t)];return r.i=s,r.j=a,n})(u)}function m(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function g(e,t){var n,r=[],s=typeof e;if(t&&"object"==s)for(n in e)try{r.push(g(e[n],t-1))}catch(e){}return r.length?r:"string"==s?e:e+"\0"}function y(e,t){for(var n,r=e+"",s=0;s<r.length;)t[p&s]=p&(n^=19*t[p&s])+r.charCodeAt(s++);return b(t)}function b(e){return String.fromCharCode.apply(0,e)}if(y(i.random(),a),e.exports){e.exports=d;try{o=n(41234)}catch(e){}}else void 0===(r=function(){return d}.call(t,n,t,e))||(e.exports=r)}("undefined"!=typeof self?self:this,[],Math)},96897:(e,t,n)=>{"use strict";var r=n(70453),s=n(30041),a=n(30592)(),i=n(75795),o=n(69675),u=r("%Math.floor%");e.exports=function(e,t){if("function"!=typeof e)throw new o("`fn` is not a function");if("number"!=typeof t||t<0||t>4294967295||u(t)!==t)throw new o("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],r=!0,l=!0;if("length"in e&&i){var c=i(e,"length");c&&!c.configurable&&(r=!1),c&&!c.writable&&(l=!1)}return(r||l||!n)&&(a?s(e,"length",t,!0,!0):s(e,"length",t)),e}},36622:e=>{"function"==typeof Object.create?e.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},81135:e=>{e.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},40537:(e,t,n)=>{var r=n(65606),s=n(96763),a=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),n={},r=0;r<t.length;r++)n[t[r]]=Object.getOwnPropertyDescriptor(e,t[r]);return n},i=/%[sdj%]/g;t.format=function(e){if(!x(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(l(arguments[n]));return t.join(" ")}n=1;for(var r=arguments,s=r.length,a=String(e).replace(i,(function(e){if("%%"===e)return"%";if(n>=s)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(e){return"[Circular]"}default:return e}})),o=r[n];n<s;o=r[++n])y(o)||!k(o)?a+=" "+o:a+=" "+l(o);return a},t.deprecate=function(e,n){if(void 0!==r&&!0===r.noDeprecation)return e;if(void 0===r)return function(){return t.deprecate(e,n).apply(this,arguments)};var a=!1;return function(){if(!a){if(r.throwDeprecation)throw new Error(n);r.traceDeprecation?s.trace(n):s.error(n),a=!0}return e.apply(this,arguments)}};var o,u={};function l(e,n){var r={seen:[],stylize:h};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),g(n)?r.showHidden=n:n&&t._extend(r,n),w(r.showHidden)&&(r.showHidden=!1),w(r.depth)&&(r.depth=2),w(r.colors)&&(r.colors=!1),w(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=c),p(r,e,r.depth)}function c(e,t){var n=l.styles[t];return n?"["+l.colors[n][0]+"m"+e+"["+l.colors[n][1]+"m":e}function h(e,t){return e}function p(e,n,r){if(e.customInspect&&n&&S(n.inspect)&&n.inspect!==t.inspect&&(!n.constructor||n.constructor.prototype!==n)){var s=n.inspect(r,e);return x(s)||(s=p(e,s,r)),s}var a=function(e,t){if(w(t))return e.stylize("undefined","undefined");if(x(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return b(t)?e.stylize(""+t,"number"):g(t)?e.stylize(""+t,"boolean"):y(t)?e.stylize("null","null"):void 0}(e,n);if(a)return a;var i=Object.keys(n),o=function(e){var t={};return e.forEach((function(e,n){t[e]=!0})),t}(i);if(e.showHidden&&(i=Object.getOwnPropertyNames(n)),N(n)&&(i.indexOf("message")>=0||i.indexOf("description")>=0))return d(n);if(0===i.length){if(S(n)){var u=n.name?": "+n.name:"";return e.stylize("[Function"+u+"]","special")}if(v(n))return e.stylize(RegExp.prototype.toString.call(n),"regexp");if(I(n))return e.stylize(Date.prototype.toString.call(n),"date");if(N(n))return d(n)}var l,c="",h=!1,k=["{","}"];return m(n)&&(h=!0,k=["[","]"]),S(n)&&(c=" [Function"+(n.name?": "+n.name:"")+"]"),v(n)&&(c=" "+RegExp.prototype.toString.call(n)),I(n)&&(c=" "+Date.prototype.toUTCString.call(n)),N(n)&&(c=" "+d(n)),0!==i.length||h&&0!=n.length?r<0?v(n)?e.stylize(RegExp.prototype.toString.call(n),"regexp"):e.stylize("[Object]","special"):(e.seen.push(n),l=h?function(e,t,n,r,s){for(var a=[],i=0,o=t.length;i<o;++i)E(t,String(i))?a.push(f(e,t,n,r,String(i),!0)):a.push("");return s.forEach((function(s){s.match(/^\d+$/)||a.push(f(e,t,n,r,s,!0))})),a}(e,n,r,o,i):i.map((function(t){return f(e,n,r,o,t,h)})),e.seen.pop(),function(e,t,n){return e.reduce((function(e,t){return t.indexOf("\n"),e+t.replace(/\u001b\[\d\d?m/g,"").length+1}),0)>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}(l,c,k)):k[0]+c+k[1]}function d(e){return"["+Error.prototype.toString.call(e)+"]"}function f(e,t,n,r,s,a){var i,o,u;if((u=Object.getOwnPropertyDescriptor(t,s)||{value:t[s]}).get?o=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(o=e.stylize("[Setter]","special")),E(r,s)||(i="["+s+"]"),o||(e.seen.indexOf(u.value)<0?(o=y(n)?p(e,u.value,null):p(e,u.value,n-1)).indexOf("\n")>-1&&(o=a?o.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+o.split("\n").map((function(e){return" "+e})).join("\n")):o=e.stylize("[Circular]","special")),w(i)){if(a&&s.match(/^\d+$/))return o;(i=JSON.stringify(""+s)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(i=i.substr(1,i.length-2),i=e.stylize(i,"name")):(i=i.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),i=e.stylize(i,"string"))}return i+": "+o}function m(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function y(e){return null===e}function b(e){return"number"==typeof e}function x(e){return"string"==typeof e}function w(e){return void 0===e}function v(e){return k(e)&&"[object RegExp]"===T(e)}function k(e){return"object"==typeof e&&null!==e}function I(e){return k(e)&&"[object Date]"===T(e)}function N(e){return k(e)&&("[object Error]"===T(e)||e instanceof Error)}function S(e){return"function"==typeof e}function T(e){return Object.prototype.toString.call(e)}function C(e){return e<10?"0"+e.toString(10):e.toString(10)}t.debuglog=function(e){if(w(o)&&(o=r.env.NODE_DEBUG||""),e=e.toUpperCase(),!u[e])if(new RegExp("\\b"+e+"\\b","i").test(o)){var n=r.pid;u[e]=function(){var r=t.format.apply(t,arguments);s.error("%s %d: %s",e,n,r)}}else u[e]=function(){};return u[e]},t.inspect=l,l.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},l.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},t.isArray=m,t.isBoolean=g,t.isNull=y,t.isNullOrUndefined=function(e){return null==e},t.isNumber=b,t.isString=x,t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=w,t.isRegExp=v,t.isObject=k,t.isDate=I,t.isError=N,t.isFunction=S,t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=n(81135);var $=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function E(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.log=function(){var e,n;s.log("%s - %s",(n=[C((e=new Date).getHours()),C(e.getMinutes()),C(e.getSeconds())].join(":"),[e.getDate(),$[e.getMonth()],n].join(" ")),t.format.apply(t,arguments))},t.inherits=n(36622),t._extend=function(e,t){if(!t||!k(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e};var A="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function R(e,t){if(!e){var n=new Error("Promise was rejected with a falsy value");n.reason=e,e=n}return t(e)}t.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(A&&e[A]){var t;if("function"!=typeof(t=e[A]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(t,A,{value:t,enumerable:!1,writable:!1,configurable:!0}),t}function t(){for(var t,n,r=new Promise((function(e,r){t=e,n=r})),s=[],a=0;a<arguments.length;a++)s.push(arguments[a]);s.push((function(e,r){e?n(e):t(r)}));try{e.apply(this,s)}catch(e){n(e)}return r}return Object.setPrototypeOf(t,Object.getPrototypeOf(e)),A&&Object.defineProperty(t,A,{value:t,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(t,a(e))},t.promisify.custom=A,t.callbackify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');function t(){for(var t=[],n=0;n<arguments.length;n++)t.push(arguments[n]);var s=t.pop();if("function"!=typeof s)throw new TypeError("The last argument must be of type Function");var a=this,i=function(){return s.apply(a,arguments)};e.apply(this,t).then((function(e){r.nextTick(i,null,e)}),(function(e){r.nextTick(R,e,i)}))}return Object.setPrototypeOf(t,Object.getPrototypeOf(e)),Object.defineProperties(t,a(e)),t}},85817:()=>{},18590:()=>{},4530:()=>{},8108:()=>{},80551:()=>{},41234:()=>{}},t={};function n(r){var s=t[r];if(void 0!==s)return s.exports;var a=t[r]={id:r,loaded:!1,exports:{}};return e[r].call(a.exports,a,a.exports,n),a.loaded=!0,a.exports}n.amdD=function(){throw new Error("define cannot be used indirect")},n.amdO={},n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var r=n(89793);nsfwjs=r})();
|